POJ 3273 Conscription(最小生成树)

来源:互联网 发布:废旧金属行情软件 编辑:程序博客网 时间:2024/05/22 00:18

Conscription

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

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
题目大意:需要征募女兵N人,男兵M人。每征募一人需要消耗10000美元。但是如果已经征募的人中有一些关系亲密的人,那么可以少花一些钱。现在给出男女之间的R个关系,征募某个人的费用是10000 - 已经征募的人中和自己亲密度的最大值。要求通过适当的征募顺序使得征募所有人所需的费用最小。

解题思路:当征募某个人a时,如果使用了a和b的关系,那么就连一条a到b的边。假设这个图中存在圈,那么无论以什么顺序征募这个圈上的所有人,都会产生矛盾。因此可以知道这个图是一片森林。反之,如果给了一片森林那么就可以使用对应的关系确定征募的顺序。因此,把人看作顶点,关系看作边,问题就转化成求解无向图中的最大权值森林问题。可以将所有边的权值取反,然后利用Kruskal算法求解。

代码如下:

#include <cstdio>#include <string>#include <algorithm>const int maxr = 50005;const int maxn = 10005;int par[maxn * 2],rank[maxn * 2];struct edge{int from;int to;int dis;};edge edges[maxr];int n,m,r;void init(){for(int i = 0;i < n + m;i++){par[i] = i;rank[i] = 0;}}int find(int x){return par[x] == x ? x : 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);}bool cmp(edge a,edge b){return a.dis < b.dis;}int Kruskal(){std::sort(edges,edges + r,cmp);int res = 0;init();for(int i = 0;i < r;i++){edge e = edges[i];if(same(e.from,e.to)) continue;unite(e.from,e.to);res += e.dis;}return res;}int main(){int t,a,b,c;scanf("%d",&t);while(t--){scanf("%d %d %d",&n,&m,&r);for(int i = 0;i < r;i++){scanf("%d %d %d",&a,&b,&c);edges[i].from = a;edges[i].to = b + n;edges[i].dis = -c;}printf("%d\n",10000 * (n + m) + Kruskal());}return 0;}


0 0
原创粉丝点击