POJ3723 Conscription

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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

1
2
71071
54223

Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <cstdio>
#include <algorithm>
using namespace std;

const int MAX_N = 20010;
const int MAX_M = 50010;

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

bool cmp(Edge a, Edge b) {
return a.cost > b.cost;
}

struct Kruskal {
int n, m;
Edge edges[MAX_M];
int par[MAX_N];

void init(int n) {
this->n = n;
m = 0;
fill(par, par+MAX_N, -1);
}

int find(int x) {
return par[x] == -1 ? x : par[x] = find(par[x]);
}

void addEdge(int u, int v, int cost) {
edges[m++] = Edge(u, v, cost);
}

int kruskal() {
int ans = 0, cnt = 0;
sort(edges, edges+m, cmp);
for (int i = 0; i < m; ++i) {
int u = find(edges[i].u),
v = find(edges[i].v);
if (u != v) {
par[u] = v;
ans += edges[i].cost;
if (++cnt >= n-1) // 树有 n 个顶点,n-1条边
break;
}
}
return ans;
}
} KK;

int main() {
int T;
scanf("%d", &T);
while (T--) {
int n, m, r;
scanf("%d %d %d", &n, &m, &r);
KK.init(n+m);
while (r--) {
int u, v, d;
scanf("%d %d %d", &u, &v, &d);
KK.addEdge(u, v+n, d);
}
printf("%d\n", (n+m)*10000-KK.kruskal());
}
return 0;
}

Analysis

  1. 花费费用最少,则选取全部顶点花费的代价最大。即最大生成树?将边权重全部取反,即是最小生成树。
  2. kruskal 求最小生成树。
  3. https://blog.csdn.net/u013480600/article/details/37996747
# POJ

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×