Kruskal思想,58pts求助
查看原帖
Kruskal思想,58pts求助
632955
伊地知虹夏楼主2023/1/31 19:11
#include<bits/stdc++.h>
using namespace std;
int n,m,k;
const int N = 2e4+5,M = 1e5+5;
struct node{
	int a,b;
}sn[M],el[M];
int c1,c2,l;
int fa[N];
bool need[M];
int ans1[M],ans2[M];
bool ans3[M];
void init(){
	for(int i = 1;i <= n;i ++)
		fa[i] = i;
	return ;
}
int find(int x){
	if(fa[x] == x) return x;
	return fa[x] = find(fa[x]);
}
int cnt = 0;
void merge(int x,int y){
	int fx = find(x),fy = find(y);
	if(fx != fy) 
		fa[fx] = fy,cnt ++;
	return ;
}
int main(){
	cin >> n >> m >> k;
	init();
	int u,v;
	bool x;
	for(int i = 1;i <= m;i ++){
		cin >> u >> v >> x;
		if(x) sn[++c1] = (node){u,v};
		else el[++c2] = (node){u,v};
	}
	for(int i = 1;i <= c1;i ++)
		merge(sn[i].a,sn[i].b);
	int nd = 0;
	for(int i = 1;i <= c2;i ++){
		int fx = find(el[i].a),fy = find(el[i].b);
		if(fx != fy){
			merge(fx,fy);
			nd ++;
			need[i] = 1;
		}
		if(cnt == n-1) break;
	}
	if(nd > k || cnt != n-1){
		cout << "no solution";
		return 0;
	}
	int less = k-nd;
	init();cnt = 0;
	for(int i = 1;i <= c2;i ++)
		if(need[i]){
			ans1[++l] = el[i].a,ans2[l] = el[i].b,ans3[l] = 0;
			merge(el[i].a,el[i].b);
		}
	for(int i = 1;i <= c2;i ++)
		if(less){
			ans1[++l] = el[i].a,ans2[l] = el[i].b,ans3[l] = 0;
			less --;
			merge(el[i].a,el[i].b);
		}
	for(int i = 1;i <= c1;i ++){
		int fx = find(sn[i].a),fy = find(sn[i].b);
		if(fx != fy){
			merge(fx,fy);
			ans1[++l] = sn[i].a,ans2[l] = sn[i].b,ans3[l] = 1;
		}
		if(cnt == n-1)
			break;
	}
	int ct = 0;
	for(int i = 1;i <= n;i ++)
	    if(fa[i] == i)
	        ct ++;
	if(cnt != n-1 || ct != 1) cout << "no solution";
	else{
		for(int i = 1;i <= l;i ++)
			cout << ans1[i] << " " << ans2[i] << " "<< ans3[i] << "\n";
	}
	return 0;
} 
2023/1/31 19:11
加载中...