题目:https://codeforces.com/problemset/problem/1559/D1
题目大意:
两张无向图,给定n个顶点 m1,m2条边 ,问最大还能再添几条边保证不会形成环路, 两张图同时添加。
题解:
1.用并查集去搜是否会构成回路,若两张图均满足 i 顶点 是 j 节点的祖先 ,则说明形成环路,不满足.否则, 满足
#define _CRT_SECURE_NO_WARNINGS
#include<vector>
#include<iostream>
using namespace std;
const int N = 1000;
int f1[N + 1];
int f2[N + 1];
int n;
int find1(int x)
{
return x == f1[x] ? x : f1[x] = find1(f1[x]);
}
int find2(int x)
{
return x == f2[x] ? x : f2[x] = find2(f2[x]);
}
void init()
{
for (int i = 1; i <= n; i++)
{
f1[i] = i;
f2[i] = i;
}
}
int main()
{
int m1, m2;
int u, v;
scanf("%d%d%d", &n, &m1, &m2);
init();
for (int i = 1; i <= m1; ++i)
{
scanf("%d %d", &u,&v);
f1[find1(u)] = find1(v);
}
for (int i = 1; i <= m2; ++i)
{
scanf("%d %d", &u, &v);
f2[find2(u)] = find2(v);
}
vector<pair<int, int>>ans;
for (int i = 1; i <= n; i++)
{
for (int j = i+1; j <= n; j++)
{
if (find1(i) != find1(j) && find2(i) != find2(j))
{
ans.push_back({ i,j });
f1[find1(i)] = find1(j);
f2[find2(i)] = find2(j);
}
}
}
printf("%d\n", ans.size());
for (auto it : ans)
{
printf("%d %d\n", it.first, it.second);
}
}