【POJ 3723】Conscription

来源:互联网 发布:sqlserver软件下载 编辑:程序博客网 时间:2024/05/16 06:06

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
25 5 84 3 68311 3 45830 0 65920 1 30633 3 49751 3 20494 2 21042 2 7815 5 102 4 98203 2 62363 1 88642 4 83262 0 51562 0 14634 1 24390 4 43733 4 88892 4 3133
Sample Output
7107154223

把人看做顶点,关系看做边,转化为求解无向图中的最大权森林问题。最大权森林问题可以通过把所有边权取反之后用最小生成树的算法求解




AC代码:

#include<iostream>#include<algorithm>#include<cstring>#include<cmath>#include<stdio.h>#include<vector>using namespace std;struct Node{    int x, y, d;}node[50002];int N, M, R, D;bool cmp(Node a, Node b){    return a.d < b.d;}int par[50002], rank[50002];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(node, node + R, cmp);    init(D);    int ans = 0;    for(int i = 0; i < R; i++)    {        Node n = node[i];        if(!same(n.x, n.y))        {            unite(n.x, n.y);            ans += n.d;        }    }    return ans;}int main(){    int t;    scanf("%d", &t);    int x, y, d;    while(t--)    {        scanf("%d%d%d", &N, &M, &R);        D = M + N;        for(int i = 0; i < R; i++)        {            scanf("%d%d%d", &x, &y, &d);            node[i].x = x;            node[i].y = N + y;            node[i].d = -d;        }        cout<<10000 * (N + M) + kruskal()<<endl;    }    return 0;}