POJ 3723 Conscription(最小生成树-Kruskal)

来源:互联网 发布:airplay怎么手机连mac 编辑:程序博客网 时间:2024/06/07 01:01

Description
温迪要组建一支军队,召集了N个女孩和M个男孩,每个人要付10000RMB,但是如果一个女孩和一个男孩有关系d的,且已经付给了其中一个人的钱,那么就可以付给另一个人10000-d元,求温迪最少要付多少钱
Input
第一行为用例组数T,每组用例第一行为三个整数N,M,R分别表示温迪要召集的女孩数,男孩数以及男女关系链条数,之后R行每行三个整数x,y,d表示x女孩与y女孩有关系d
Output
对于每组用例,输出温迪最少付钱数
Sample Input
2

5 5 8
4 3 6831
1 3 4583
0 0 6592
0 1 3063
3 3 4975
1 3 2049
4 2 2104
2 2 781

5 5 10
2 4 9820
3 2 6236
3 1 8864
2 4 8326
2 0 5156
2 0 1463
4 1 2439
0 4 4373
3 4 8889
2 4 3133
Sample Output
71071
54223
Solution
花钱最少即为省钱最多,建一棵最小生成树,用Kruskal算法,将边的权值设为-d即可
Code

#include<cstdio>#include<iostream>#include<algorithm>using namespace std;#define maxn 50001struct edge{    int u,v,cost;};int T,N,M,R;int x[maxn],y[maxn],d[maxn];edge es[maxn];int par[maxn];int rank[maxn];bool comp(const edge&e1,const edge&e2){    return e1.cost<e2.cost;}void init(int n){    for(int i=0;i<n;i++)    {        par[i]=i;        rank[i]=0;    }}int find(int x){    if(par[x]==x)        return x;    else        return par[x]=find(par[x]);}void unite(int x,int y){    x=find(x);    y=find(y);    if(x==y)        return ;    if(rank[x]<rank[y])        par[x]=y;    else    {        par[y]=x;        if(rank[x]==rank[y])            rank[x]++;    }}bool same(int x,int y){    return find(x)==find(y);}int kruskal(){    sort(es,es+R,comp);    init(N+M);    int res=0;    for(int i=0;i<R;i++)    {        edge e=es[i];        if(!same(e.u,e.v))        {            unite(e.u,e.v);            res+=e.cost;        }    }    return res;}int main(){    scanf("%d",&T);    while(T--)    {        scanf("%d%d%d",&N,&M,&R);        for(int i=0;i<R;i++)            scanf("%d%d%d",&x[i],&y[i],&d[i]);        for(int i=0;i<R;i++)            es[i]=(edge){x[i],y[i]+N,-d[i]};        printf("%d\n",10000*(N+M)+kruskal());       }    return 0;}
0 0