POJ 3723 Conscription【招募士兵】

来源:互联网 发布:php curl 编码 编辑:程序博客网 时间:2024/06/05 09:40

原题链接

思路:把男生女生都当作顶点,把把亲密度的负数当作权值,就是最小生成树问题。

AC代码:

#include <iostream>#include <cstdio> #include <algorithm>#include <cstdlib>#include <cstring>using namespace std;//《挑战》 P109//把男生女生都当作顶点,把把亲密度的负数当作权值,就是最大生成树问题//优化并查集 struct edge{    int from,to,cost;}e[70000];int T,N,M,R;  //测试用例,女生数,男生数,边(有亲密度的组数)bool cmp(edge a,edge b){    return a.cost>b.cost;}//优化的并查集int p[100000];  //根 int findset(int x)  //找根并换根 {    int px=x,i;    while(px!=p[px])  px=p[px];    while(x!=px){        i=p[x];        p[x]=px;        x=i;    }     return px;} int main(){    int j;    scanf("%d",&T);    while(T--){        scanf("%d %d %d",&N,&M,&R);         long long int res=(M+N)*10000;        for(j=0;j<M+N;j++)  p[j]=j;        for(j=0;j<R;j++){            scanf("%d %d %d",&e[j].from,&e[j].to,&e[j].cost);            getchar();            e[j].to+=N;        }        sort(e,e+R,cmp);        for(j=0;j<R;j++){            int x=findset(e[j].from),y=findset(e[j].to);            if(x!=y){                res-=e[j].cost;                p[x]=y;            }        }        printf("%lld\n",res);    }    return 0;}
1 0