1300*C. Rumor(并查集&贪心)

1300*C. Rumor(并查集&贪心)_第1张图片

1300*C. Rumor(并查集&贪心)_第2张图片

1300*C. Rumor(并查集&贪心)_第3张图片

解析:

        并查集,求每个集合的最小费用。

         每次合并集合的时候,根节点保存当前集合最小的费用。 

#include
using namespace std;
#define int long long
const int N=1e5+5;
int n,m,a[N],p[N],cnt[N];
int find(int x){
	return x==p[x]?x:p[x]=find(p[x]);
}
signed main(){
	scanf("%lld%lld",&n,&m);
	for(int i=1;i<=n;i++){
		scanf("%lld",&a[i]);
		p[i]=i;
	}
	while(m--){
		int x,y;
		scanf("%lld%lld",&x,&y);
		x=find(x),y=find(y);
		if(a[x]<=a[y]) p[y]=x;
		else p[x]=y;
	}
	int ans=0;
	for(int i=1;i<=n;i++){
		if(i==p[i]) ans+=a[i];
	}
	printf("%lld",ans);
	return 0;
}

你可能感兴趣的:(codeforces,c语言,图论,开发语言,数据结构,算法,c++)