86tps求调
查看原帖
86tps求调
942071
_xzh_楼主2024/8/19 09:49

rt,只扫了一遍Kruskal,但好像没问题

#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m,k,tot,l;
int root[100005];
struct Edge{
	int u,v,w;
}e[100005],ans[100005];
bool cmp(Edge a,Edge b){
	return a.w<b.w;
}
int find(int x){
	if(root[x]==x)return x;
	return root[x]=find(root[x]);
}
signed main(){
	cin>>n>>m>>k;
	for(int i=1;i<=n;i++){
		root[i]=i;
	}
	for(int i=1;i<=m;i++){
		int u,v,w;
		cin>>u>>v>>w;
		e[++tot].u=u;
		e[tot].v=v;
		e[tot].w=w;
	}
	sort(e+1,e+tot+1,cmp);
	int cnt=0;
	for(int i=1;i<=m;i++){
		if(find(e[i].u)==find(e[i].v)){
			continue;
		}
		if(cnt==k&&e[i].w==0)continue;
		int fu=find(e[i].u),fv=find(e[i].v);
		if(fu!=fv){
			if(e[i].w==0)cnt++;
			ans[++l].u=e[i].u;
			ans[l].v=e[i].v;
			ans[l].w=e[i].w;
		}
		root[fu]=fv;
	}
	if(cnt<k)cout<<"no solution"<<endl;
	else {
		for(int i=1;i<=l;i++){
			cout<<ans[i].u<<" "<<ans[i].v<<" "<<ans[i].w<<endl;
		}
	}
	return 0;
}

2024/8/19 09:49
加载中...