题意是给出n个城市,n-1条路,每天会修路(删除原本的一条路,然后增添一条新路)
这题的亮点就在路只有n-1条,要联通的话只能有一个祖先,且不存在回路...
故只要删除有回路的,然后把每个不相连的路连接起来即可....
#include<bits/stdc++.h>
using namespace std;
const int N = 1111;
int fa[N];
struct node
{
int x,y;
}a[N];
int b[N];
int find(int x)
{
int r=x;
while(fa[r]!=r) r=fa[r];
int i=x,j;
while(i!=r) {
j=fa[i];
fa[i]=r;
i=j;
}
return r;
}
int main()
{
int n,i,j,x,y,cnt;
cin>>n;
for(i=1;i<=n;i++) fa[i]=i;
cnt=0;
for(i=1;i<n;i++) {
cin>>x>>y;
int fx=find(x);
int fy=find(y);
if(fx!=fy) fa[fx]=fy;
else {
a[++cnt].x=x;
a[cnt].y=y;
}
}
cnt=0;
for(i=1;i<=n;i++) {
if(find(i)==i) b[++cnt]=i;
}
printf("%d\n",cnt-1);
for(i=1;i<cnt;i++) {
printf("%d %d %d %d\n",a[i].x,a[i].y,b[i],b[i+1]);
}
return 0;
}