Off white cow month season 18 H Forsaken like a unique solution to a problem tree (minimum spanning tree)

Topic Link

Subject to the effect

FIG point a given number n and m edges, the right side of each value w, you can remove some of the edges, so that the remaining sides of the minimum spanning tree of the same size and the minimum spanning tree is unique in FIG. Now we want to know the weight of the side is removed and the minimum number?

Topic ideas

Unique minimum spanning tree to be formed, there is no other side of the minimum spanning tree can be added at minimum spanning tree. We can find all the edge weights can be added in the calculation of the minimum spanning tree minimum spanning tree and, minus a minimum spanning tree and the right side is the answer.

It is really difficult to understand, but do not know why I did not write it, to understand the nature of what a direct kruskal

Code

#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=2e5+5;
int n,m,fa[maxn];
ll ans;
struct node{
	int u,v,w;
}e[maxn];
bool cmp(node a,node b){
	return a.w<b.w;
}
int findd(int x){
	if(x==fa[x])
		return x;
	return fa[x]=findd(fa[x]);
}
int main(){
	scanf("%d %d",&n,&m);
	for(int i=1;i<=n;i++){//并查集初始化 
		fa[i]=i;
	}
	for(int i=1;i<=m;i++){
		scanf("%d %d %d",&e[i].u,&e[i].v,&e[i].w);
	}
	sort(e+1,e+1+m,cmp);
	for(int l=1,r=1;l<=m;l=r){//注意直接l=r为下一个条件 
		while(r<=m&&e[l].w==e[r].w){
			r++;
		}
		for(int i=l;i<r;i++){//表示l到r-1得边权值都相等 
			if(findd(e[i].v)!=findd(e[i].u)){
				ans+=e[i].w;//找总边权值 
			}
		}
		for(int i=l;i<r;i++){//找最小生成树得边权值 
			if(findd(e[i].v)!=findd(e[i].u)){
				ans-=e[i].w;
				fa[findd(e[i].v)]=findd(e[i].u);
			}
		}
	}
	printf("%lld",ans);
	return 0;
} 
Published 68 original articles · won praise 2 · Views 2243

Guess you like

Origin blog.csdn.net/m0_46209312/article/details/105265232
Recommended