求调 不明白为什么最后一个样例WA了
查看原帖
求调 不明白为什么最后一个样例WA了
1785911
asuka_qwq楼主2025/7/18 18:13
#include<bits/stdc++.h>
#define int long long
using namespace std;

const int N=5e3+7;
int fa[N];
int n,m;
int tot;


struct Node{
	int h,ver,w;
}e[2*N*N];

bool cmp(Node x,Node y){
	return x.w<y.w;
}

void add(int u,int v,int w){
	++tot;
	e[tot].h=u;
	e[tot].ver=v;
	e[tot].w=w;	
}

int find(int x){
	if(fa[x]==x)return x;
	return fa[x]=find(fa[x]);
}

signed main(){
	ios::sync_with_stdio(NULL);
	cin.tie(0);cout.tie(0);
	
	cin>>n>>m;
	for(int i=1;i<=n;i++)fa[i]=i;
	while(m--){
		int x,y,z;cin>>x>>y>>z;
		add(x,y,z);
		add(y,x,z);
	}
	sort(e+1,e+1+tot,cmp);
	int cnt=1,ans=0;
	for(int i=1;cnt<n;i++){
		int u=e[i].h,v=e[i].ver,w=e[i].w;
		if(find(u)==find(v))continue;
		cnt++;
		ans+=w;
		fa[find(u)]=find(v);
	}
	cout<<ans;
	
	return 0;
}
2025/7/18 18:13
加载中...