https://www.luogu.com.cn/problem/CF25D
前言
乱做的 做的时候还怀疑能不能满足 但是就是过了样例
思路
一开始 以为是图论 这是需要dfs遍历吗? 怎么判断集合呢
一说到集合 就 搞到了 并查集
然后就没有然后了 代码很简单
CODE
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e3+10;
int p[N],n;
struct node
{
int to,ed;
} num[N];
int idx;
struct nd
{
int x,y;
int to,ed;
} add[N];
int id ;
int find(int x)
{
if(x!=p[x])
return p[x] =find(p[x]);
return p[x];
}
void solve()
{
cin>>n;
for(int i =1; i<=n; i++)
p[i]=i;
for(int i =1 ; i<=n-1; i++)
{
int a,b;
cin>>a>>b;
int fa= find(a);
int fb= find(b);
if(fa == fb)
{
num[++idx].to = a;
num[idx].ed = b;
//cout<<a<<" "<<b<<endl;
}
p[fa] =fb;
}
// for(int i=1;i<=idx;i++)
//cout<<num[i].to<<" "<<num[i].ed<<endl;
for(int i=1; i<n; i++)
for(int j=i+1; j<=n; j++)
{
int fa =find(i);
int fb =find(j);
if(fa!=fb)
{
p[fb] =fa;
add[++id].to = num[idx].to;
add[id].ed =num[idx--].ed;
add[id].x = i;
add[id].y = j;
}
}
cout<<id<<endl;
for(int i=1; i<=id; i++)
cout<<add[i].to<<" "<<add[i].ed<<" "<<add[i].x<<" "<<add[i].y<<endl;
}
int main()
{
ios::sync_with_stdio(false);
solve();
return 0;
}