poj3723 Conscription Kruscal算法最大生成森林

Conscription
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 9902   Accepted: 3502

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 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



根据题意,只要用排序优化的Kruscal算法求出带有最大权值和的生成森林,森林的权值和是ans,则(N + M) * 10000 - ans即为最小cost


#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>

using namespace std;

struct Edge {
	int u, v, w;
	Edge() {}
	Edge(int u, int v, int w) : u(u), v(v), w(w) {}
};

vector<Edge> edges;

int N, M, R;
int p[20010];

bool cmp(const Edge a, const Edge b) {
	return a.w > b.w;  //从大到小排序
}

int Find(int x) {  //并查集
	return p[x] == x ? x : p[x] = Find(p[x]);
}

int Kruscal() {
	for (int i = 0; i < N + M; i++) p[i] = i;
	sort(edges.begin(), edges.end(), cmp);
	int ans = 0;
	for (int i = 0; i < edges.size(); i++) {
		int x = Find(edges[i].u), y = Find(edges[i].v);
		if (x != y) {
			p[y] = x;
			ans += edges[i].w;
		}
	}
	return (N + M) * 10000 - ans;
}

int main()
{
	int T;
	scanf("%d", &T);
	while (T--) {
		edges.clear();
		scanf("%d%d%d", &N, &M, &R);
		int u, v, w;
		for (int i = 0; i < R; i++) {
			scanf("%d%d%d", &u, &v, &w);
			//为了分别girl和boy,将v平移N,这么做放在一个数组里也方便计算并查集
			edges.push_back(Edge(u, v + N, w));
		}
		printf("%d\n", Kruscal());
	}
	return 0;
}



你可能感兴趣的:(算法,最小生成树,ACM,poj,图论)