37求调
  • 板块P1807 最长路
  • 楼主G_MARiA
  • 当前回复1
  • 已保存回复1
  • 发布时间2025/8/29 17:10
  • 上次更新2025/8/29 17:31:35
查看原帖
37求调
1524918
G_MARiA楼主2025/8/29 17:10

我看这题类似最短路打了个最短路后反过来的

#include<bits/stdc++.h>
using namespace std;
struct node{
	int x,y,z;
}e[500005];
int anc[1510];
int n,m;
int ans=0,cnt=0;
bool cmp(node a,node b){
	return a.z>b.z;
}
int find(int x){
	if(x!=anc[x]){
		anc[x]=find(anc[x]);
	}
	return anc[x];
}
int main(){
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++){
		anc[i]=i;
	}
	for(int i=1;i<=m;i++){
		scanf("%d%d%d",&e[i].x,&e[i].y,&e[i].z);
	}
	sort(e+1,e+m+1,cmp);
	for(int i=1;i<=m;i++){
		int fx,fy;
		fx=find(e[i].x);
		fy=find(e[i].y);
		if(fx!=fy){
			anc[fy]=fx;
			ans+=e[i].z;
			cnt++;
		}
		if(cnt==n) break;
	}
	if(cnt==n-1) cout<<ans;
	else cout<<"-1";
	return 0;
}
2025/8/29 17:10
加载中...