知识点:并查集
这个1900的题还是比较简单的,这种生成树的简单题都可以用并查集想一想,我们就输入的时候连接边,除非边两边的元素已经在一个集合里面了,那么这个边我们就储存起来,后面备用,然后我们开始遍历可以用来连接不同连通块的边,每用一个边,都从第二个结点向后找一个和第一个元素不在一个连通块里面的结点,这就是一个答案,输出,输出完之后不要忘记要把这两个不同的连通块相连一下,就是因为这个wa了一次
#include <bits/stdc++.h>
using namespace std;
const int N = 1005;
int fa[N], cnt;
pair<int, int> a[N];
int get(int x) {
if (x == fa[x]) return x;
return fa[x] = get(fa[x]);
}
void merge(int x, int y) {
fa[get(x)] = get(y);
}
int main() {
for (int i = 0; i < N; i++) fa[i] = i;
int n;
cin >> n;
for (int i = 1; i < n; i++) {
int x, y;
cin >> x >> y;
if (get(x) != get(y)) merge(x, y);
else a[++cnt] = make_pair(x, y);
}
int tot = 0;
for (int i = 1; i <= n; i++) {
if (i == get(i)) tot++;
}
cout << tot - 1 << '\n';
for (int i = 1; i <= cnt; i++) {
for (int j = 2; j <= n; j++) {
if (get(j) != get(1)) {
cout << a[i].first << ' ' << a[i].second << ' ';
cout << 1 << ' ' << j << '\n';
merge(1, j);
break;
}
}
}
return 0;
}