poj3723 Conscription

来源:互联网 发布:淘宝网店设计教程 编辑:程序博客网 时间:2024/05/16 13:52

这个题目大意就不写了,注意男生和女生区分的话可以:(女:1,2,3…;男:n+1,n+2,n+3…),把两人之间的亲密度当做点与点之间有权值,就是求最大生成树,把权值换成负的,就是求最小生成树了。
数据输入量很大,要用scanf,不然会TLE。(poj教你养成随手scanf和printf的习惯,因为poj的题目老是卡这个)
代码如下:

#include <cstdio>#include <iostream>#include <algorithm>#include <cstring>#include <queue>using namespace std;const int MAXN = 200000+5;int n,m,r,tot,f[MAXN];struct Edge{    int from,to,cost;}e[MAXN];bool cmp(Edge u , Edge v){    return u.cost < v.cost;}int find(int x){    return f[x] == x?x:f[x] = find(f[x]);}void build(int f,int t,int d){    e[++tot].from = f;    e[tot].to = t;    e[tot].cost = d;}int main(){    int t;    scanf("%d",&t);    while(t --)    {        int ans = 0;tot=0;        scanf("%d%d%d",&n,&m,&r);        for(int i =0 ; i <= n+m ; i ++)        f[i] = i;        for(int i = 1; i <= r;  i ++)        {            int aa,bb,cc;            scanf("%d%d%d",&aa,&bb,&cc);            build(aa,bb+n,-cc);        }        sort(e+1,e+tot+1,cmp);        for(int i =1; i <= tot ; i ++)        {            int xx = find(e[i].from );            int yy = find(e[i].to );            if(xx!=yy)            {                f[xx] = yy;                ans += e[i].cost;            }               }        cout <<(n+m)*10000+ans<<endl;    }    return 0;}
原创粉丝点击