(Luogu) P1525 关押罪犯 (并查集)

传送门

题目大意:1~n个人,一张关系网,连线权值代表起冲突的影响力,将n个人分成两部分,求最小的冲突事件影响力。如图

(Luogu) P1525 关押罪犯 (并查集)_第1张图片答案为3512.

解题思路:我们当然不希望权值大的边存在,所以将边从大到小排序,逐个处理,边所对的两方各为敌方,我们应该将一个人和他敌人的敌人并到一个集合,每一次合并都相当于去掉了这条边,从大到小去,当发现了这条边的两段已经在一个集合了,说明在前面合并去掉大边的时候,合并了两段,所以不可避免地这条边的权值就是答案。当合并了m条边时还没有输出,那就说明没有冲突。

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long ll;
const ll inf=0x3f3f3f3f;
const int maxn=2e4+5;
int fa[maxn],rk[maxn],b[maxn];//b数组用来记录最大的仇人
int n,m; 
struct edge{
	int s,e,w;
}eg[100005];
bool cmp(edge a,edge b){
	return a.w>b.w;
}
void init(){
	for(int i=0;i>n>>m;
	for(int i=1;i<=m;++i){
		cin>>eg[i].s>>eg[i].e>>eg[i].w;
	}
	sort(eg+1,eg+1+m,cmp);
	int i,s,e;
	for(i=1;i<=m;++i){
		s=eg[i].s,e=eg[i].e;
		if(ck(s,e)){
			cout<

 

你可能感兴趣的:(Luogu,并查集)