poj 3732 Conscription(kruscal+最大权森林)(kruscal模板)

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 10332   Accepted: 3633

Description

Windy has a country, and he wants to build an army to protect his country. He has picked up N girls and M boys and wants to collect them to be his soldiers. To collect a soldier without any privilege, he must pay 10000 RMB. There are some relationships between girls and boys and Windy can use these relationships to reduce his cost. If girl x and boy y have a relationship d and one of them has been collected, Windy can collect the other one with 10000-d RMB. Now given all the relationships between girls and boys, your assignment is to find the least amount of money Windy has to pay. Notice that only one relationship can be used when collecting one soldier.

Input

The first line of input is the number of test case.
The first line of each test case contains three integers, NM and R.
Then R lines followed, each contains three integers xiyi and di.
There is a blank line before each test case.

1 ≤ NM ≤ 10000
0 ≤ R ≤ 50,000
0 ≤ xi < N
0 ≤ yi < M
0 < di < 10000

Output

For each test case output the answer in a single line.

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

Source

POJ Monthly Contest – 2009.04.05, windy7926778

题目大意:

        要招n女,m男,每招一个人需要10000元,但是有一些男女有亲密度,为d,比如第i个女和第j个男有d的亲密度,那么他们任意一个如果已经被招,则招另一个只需10000 - d元,问最少要用多少元招完这n女m男。

解题思路:

        用点表示男女,边权为对应两人亲密度,选一条边表示用到了对应两个人的亲密度,那么只要这些边不成环,就一定有一种顺序把选的边都用上(拓扑排序一下得到顺序),所以就要求这个图最大权森林,权值即为省的钱数。总钱数-省的钱数就是答案。



#include<stdio.h>
#include<algorithm>
#define N 20005
using namespace std;
int par[N],ran[N];
struct edge{int u,v,w;}e[50005];
int t,n,m,r;
int cmp(edge a,edge b)//最小生成树只需要这里改一下排序顺序
{
    return a.w>b.w;
}
void init(int n)
{
    for(int i=0;i<=n;i++)
    {
        par[i]=i;
        ran[i]=0;
    }
}
int find(int x)
{
    if(par[x]==x)return x;
    return par[x]=find(par[x]);
}
bool un(int x,int y)
{
    x=find(x);
    y=find(y);
    if(x==y)return 0;
    if(ran[x]<ran[y]) par[x]=y;
    else par[y]=x;
    if(ran[x]==ran[y])ran[x]++;
    return 1;
}

int kru()
{
    sort(e,e+r,cmp);
    int ans=0;
    for(int i=0;i<r;i++)
        if(un(e[i].u,e[i].v))ans+=e[i].w;
    return ans;
}

int main()
{
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d%d",&n,&m,&r);
        init(n+m);
        for(int i=0;i<r;i++)
        {
           scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
           e[i].v+=n;
        }
        printf("%d\n",10000*(n+m)-kru());
    }
}


你可能感兴趣的:(最小生成树,poj)