天天看点

最小生成树(士兵招募)

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

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<vector>
#include<queue>
#include<set>
#define IL inline
#define x first
#define y second
typedef long long ll;
using namespace std;
const	int N=2e4+10,M=50010;
struct node{
	int a;
	int b;
	int w;
	bool operator <(const node&W) const
	{
		return w<W.w;
	}
}edge[M];
int p[N];
int find(int x)
{
	if(x!=p[x])
	p[x]=find(p[x]);
	return p[x];
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		int n,m,z;
		scanf("%d%d%d",&n,&m,&z);
		for(int i=0;i<=n+m;i++)
		p[i]=i;
		ll ans=10000*(n+m);
		for(int i=0;i<z;i++)
		{
			int a,b,c;
			scanf("%d%d%d",&a,&b,&c);
			edge[i].a=a,edge[i].b=b+n,edge[i].w=-c;
		}
		sort(edge,edge+z);
		for(int i=0;i<z;i++)
		{
			int a=edge[i].a,b=edge[i].b,c=edge[i].w;
			a=find(a),b=find(b);
			if(a!=b)
			{
				p[a]=b;
				ans=ans+c;
			}
		}
		printf("%lld\n",ans);
	 } 
    return 0;
}