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, N, M and R.
Then R lines followed, each contains three integers xi, yi and di.
There is a blank line before each test case.1 ≤ N, M ≤ 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 7815 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
题目大意:
需要征募女兵N人, 男兵M人. 每征募一个人需要花费10000美元. 带式如果已经征募的人中有一些关系亲密的人, 那么可以少花一些钱. 给出若干的男女之前的1~9999指尖的亲密关系,征募某个人的费用是10000-(已经招募的人中和自己的亲密度最的最大值). 要求通过适当的征募顺序使得征募所有人所用的费用最小.
题解:
在征募某个人a时,如果使用来a和b之间的关系,那么就连一条a到b的边.假设这个图中存在圈,那么无论以什么顺序征募这个圈上的所有人, 都会产生矛盾.(只有男女关系是产生不了圈的…)因此可以直到这个图是一片森林. 反之,如果给了一片森林那么就可以使用对应的关系确定征募的顺序.
可以把人看作顶点, 关系看作边,这个问题就可以转化为求解无向图中的最大权森林问题.最大权森灵问题可以通过把所有边取反之后用最小生成树的算法求解.
代码:
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdio>
#define MAX_R 60000
#define MplusN 30000
using namespace std;
struct Edge {
int u, v, w;
};
int N, M, R;
int f[MplusN];
vector<Edge> edges(MAX_R);
bool cmp(Edge &a, Edge &b) {
return a.w < b.w;
}
void f_init(int n) {
for (int i = 0; i <= n; i++)
f[i] = i;
}
int find(int x) {
if (f[x] == x) return x;
else return f[x] = find(f[x]);
}
void join(int x, int y) {
int fx = find(x), fy = find(y);
if (fx != fy) {
f[fx] = fy;
}
}
int kruskal() {
int sum = 0;
f_init(N+M);
sort(edges.begin(), edges.begin() + R, cmp);
vector<Edge>::iterator i;
for (i = edges.begin(); i < edges.begin() + R; i++) {
int u = i->u, v = i->v;
int fu = find(u), fv = find(v);
if (fu != fv) {
join(fu, fv);
sum += i->w;
}
}
return sum;
}
int main() {
int n;
int x, y, d;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d%d%d", &N, &M, &R);
for (int i = 0; i < R; i++) {
scanf("%d%d%d", &x, &y, &d);
edges[i].u = x;
edges[i].v = y + N;
edges[i].w = -d;
}
cout << 10000 * (N + M) + kruskal() << endl;
}
return 0;
}