最小生成树(士兵招募)

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

解题报告:我是看着白书的做的,白书中说该图中不能存在圈,然后思路就是先把(n+m)*10000给算出来,然后存的是逆向的边,注意男士兵的节点要n+男生的编号,否则会与女士兵重复,然后女士兵是从0开始的,这道题的坑点,我果断踩坑。。。在更新p数组的时候没有更新0这个点,然后就是kruskal的模板题了。

#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;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值