求助大佬,25分
查看原帖
求助大佬,25分
660708
llwarll楼主2022/7/7 08:23

1340 兽径管理

#include<bits/stdc++.h>
using namespace std;
int n,t,fa[500];
struct rec{
	int x,y,w,t;
}edge[40000];
bool cmp(rec a,rec b){
	return a.w<b.w;
}
int get(int x){
	if(x==fa[x])return x;
	return fa[x]=get(fa[x]);
}
void curuscl(int opt){
	int ans=0;
	int k=0;
	for(int i=1;i<=n;i++)fa[i]=i;
	for(int i=1;i<=n;i++){
		int x=get(edge[i].x),y=get(edge[i].y);
		if(x!=y&&edge[i].t<=opt){
			fa[x]=y;
			ans+=edge[i].w;
			k++;
		}
		if(k==n-1){
		cout<<ans<<endl;
		return ;
		}
	}
	cout<<-1<<endl;

}
int main(){
	cin>>n>>t;
	for(int i=1;i<=t;i++){
		cin>>edge[i].x>>edge[i].y>>edge[i].w;
		edge[i].t=i;
	}
	for(int i=1;i<=n;i++)fa[i]=i;
	sort(edge+1,edge+t+1,cmp);
	for(int i=1;i<=t;i++)
		curuscl(i);
	return 0;
}
2022/7/7 08:23
加载中...