对拍时如何生成一棵树

这是困扰我很久的难题

经过巨佬提示,我发现很简单

--> 随便建图,并查集判环,建到n-1条边就可以了

#include<bits/stdc++.h>
using namespace std;
int n,m,cnt,fa[100015];
int find(int x){
	return x==fa[x]?x:fa[x]=find(fa[x]);
}
int main()
{
	freopen("1.in","w",stdout);
	srand(time(0));
	n=rand()%100000+10;
	cout<<n<<endl;
	for(int i=1;i<=n;i++)fa[i]=i;
	while(cnt<n-1){
		int x=rand()%n+1,y=rand()%n+1;
		int x1=find(x),y1=find(y);
		if(x1!=y1) fa[x1]=y1,cnt++,cout<<x<<" "<<y<<endl;
	}
}

猜你喜欢

转载自blog.csdn.net/sslz_fsy/article/details/83064905