POJ - 3723 Conscription 最小生成树

poj3723

大意:题目给定n个女同学,m个男同学,让后给若干个男女关系,每个关系都有一个特定值c,雇佣一个人10000元,而如果当前雇佣的人与已经雇佣的人有关系的话,雇佣钱数就可以-c。要求雇佣所有人花的最少钱数。
还是比较简单的,被自己的假算法骗到了。。。把给定的若干关系看成一个个连通块,对于每个连通块,拿10000元买一个人,让后剩下的人就都可以用优惠之后的价格购买了。这也是比较显然的,因为每个优惠关系最终只能优惠到一个人,需要另一个被雇佣了才能优惠嘛,所以跑一遍最小生成树,让后加上连通块个数*10000即可。

#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<cmath>
#include<cctype>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<sstream>
#define X first
#define Y second
#define L (u<<1)
#define R (u<<1|1)
#define Mid (tr[u].l+tr[u].r>>1)
#define Len(u) (tr[u].r-tr[u].l+1)
#define pb push_back
#define mk make_pair
using namespace std;

typedef long long LL;
typedef pair<int,int> PII;

const int N=50010,mod=1e9+7,INF=0x3f3f3f3f;
const double eps=1e-6;

int n,m,r;
int p[N];
struct Node
{
    int a,b,w;
    bool operator < (const Node &W) const
    {
        return w<W.w;
    }
}edge[N];

void init()
{
    for(int i=0;i<=n+m;i++) p[i]=i;
}

int find(int x)
{
    return x==p[x]? p[x]:p[x]=find(p[x]);
}

int main()
{
//	ios::sync_with_stdio(false);
//	cin.tie(0);

    int t; scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d%d",&n,&m,&r); init();
        for(int i=1;i<=r;i++)
        {
            int a,b,c; scanf("%d%d%d",&a,&b,&c); b+=n;
            edge[i]={a,b,10000-c};
        }
        LL cos=0; sort(edge+1,edge+1+r);
        for(int i=1;i<=r;i++)
        {
            int a=edge[i].a,b=edge[i].b,w=edge[i].w;
            int pa=find(a),pb=find(b);
            if(pa==pb) continue;
            cos+=w; p[pa]=pb;
        }
        for(int i=0;i<n+m;i++) if(find(i)==i) cos+=10000;
        printf("%lld\n",cos);
    }



	return 0;
}
/*

*/









猜你喜欢

转载自blog.csdn.net/DaNIelLAk/article/details/107723153