PKU-3723(Kruskal())

来源:互联网 发布:无冬之夜mac 编辑:程序博客网 时间:2024/06/09 21:35

Conscription
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 5981 Accepted: 2054

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

Source

POJ Monthly Contest – 2009.04.05, windy7926778

这也是一道很不错的题目呀,,,猛一看还以为是二分匹配呢,,其实是用Kruskal()解决最小费用的题目,

很不错,让我给A了

代码:

#include <stdio.h>#include <string.h>#include <iostream>#include <string>#include <algorithm>using namespace std;struct Edge{int a;int b;int val;}e[50005];int N;int M;int R;int set[22222];bool cmp(const Edge &a, const Edge &b){return a.val < b.val;}void Init(){for (int i = 0; i < N + M; i++){set[i] = i;}}int find(int x){return set[x] = (set[x] == x ? x : find(set[x]));}int Kruskal(){int val = 0;for (int i = 0; i < R; i++){int a = find(e[i].a);int b = find(e[i].b);if (a != b){set[b] = a;val += e[i].val;}}int cnt = 0;for (int i = 0; i < N + M; i++){if (set[i] == i){cnt++;}}return val + cnt * 10000;}/*void Print(){for (int i = 0; i < R; i++){printf("a = %d, b = %d, val = %d\n", e[i].a, e[i].b, e[i].val);}}*/int main(){int T;scanf("%d", &T);while (T--){int a, b, val;scanf("%d%d%d", &N, &M, &R);Init();for (int i = 0; i < R; i++){scanf("%d%d%d", &a, &b, &val);b = b + N;e[i].a = a;e[i].b = b;e[i].val = 10000 - val;}sort(e, e + R, cmp);//Print();int ans = Kruskal();printf("%d\n", ans);}return 0;}




原创粉丝点击