蒟蒻WA求调
查看原帖
蒟蒻WA求调
619237
LY00000楼主2024/7/4 20:55

贪心+Kruskal 但是不知道哪里处理错了。。

#include <bits/stdc++.h>
//#define maxn
#define M 100010
using namespace std;
int n,m;
struct rec{ 
	int x,y;
	long long w;
	operator<(const rec &x)const{
		return w<x.w;
	}
}edge[M*4];
int fa[M];
long long sum;
int num;
int _find(int xx){
	if(fa[xx]==xx)return xx;
	return fa[xx]=_find(fa[xx]);
}
bool uniom(int xx,int yy){
	if(_find(xx)!=_find(yy)){
		fa[xx]=yy;
		num++;
		return true;
	}
	return false;
}
int tot;
long long a[M*2];
long long minn=1e18;
int t;
int main(){
	//freopen("*.in","r",stdin);
	//freopen("*.out","w",stdout);
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++){
		scanf("%lld",&a[i]);
		if(minn>a[i]){
			minn=a[i];
			t=i;
		}
	}
	for(int i=1;i<=n;i++){
		if(t!=i){
			edge[++tot].x=i;
			edge[tot].y=t;
			edge[tot].w=a[i]+a[t];
		}
	}
	for(int i=1;i<=m;i++){
		int p,q;
		long long k;
		scanf("%d%d%lld",&p,&q,&k);
		edge[++tot].x=p;
		edge[tot].y=q;
		edge[tot].w=k;
	}
	sort(edge+1,edge+1+tot);
	for(int i=1;i<=n;i++)fa[i]=i;
	for(int i=1;i<=tot;i++){
		if(uniom(edge[i].x,edge[i].y)){
			sum+=edge[i].w;
			if(num==n)break;
		}
	}
	printf("%lld\n",sum);
	return 0;
	//fclose(stdin);
	//fclose(stdout); 
}
2024/7/4 20:55
加载中...