建图,然后,输入的能够节省的钱,变负数存为权值,
首先按每个人都选出来算 ans
然后用克鲁斯卡尔算法求最小生成树
得到的答案就是 最小花费了
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cmath>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <ctype.h>
#include <vector>
#include <algorithm>
#include <sstream>
#define PI acos(-1.0)
#define in freopen("in.txt", "r", stdin)
#define out freopen("out.txt", "w", stdout)
using namespace std;
typedef long long ll;
const int maxn = 100000 + 7, INF = 0x3f3f3f3f;
int n, m, k, ans;
int f[maxn];
struct edge {
int u, v, cost;
}a[maxn];
bool cmp(edge a, edge b) {
return a.cost < b.cost;
}
void init() {
int u, v, e;
for(int i = 0; i < k; ++i) {
scanf("%d %d %d", &u, &v, &e);
a[i].u = u;
a[i].v = v+n;
a[i].cost = -1*e;
}
sort(a, a+k, cmp);
for(int i = 0; i <= (m+n); ++i)
f[i] = i;
}
int find_(int u) {
if(f[u] == u) return u;
return f[u] = find_(f[u]);
}
void kruscal() {
for(int i = 0; i < k; ++i) {
int u = find_(a[i].u), v = find_(a[i].v), cost = a[i].cost;
if(u == v) continue;
else {
f[u] = v;
ans += cost;
}
}
}
int main() {
int T;
scanf("%d", &T);
while(T--) {
scanf("%d %d %d", &n, &m, &k);
init();
ans = (n+m)*10000;
kruscal();
printf("%d\n", ans);
}
return 0;
}