Codeforces Round #738 (Div. 2) D1. Mocha and Diana (Easy Version)(并查集+无环树)
https://codeforces.com/contest/1559/problem/D1
题目大意:
给定两棵树,树的节点都是从1到n,这两棵树分别建了m1和m2条边;
问我们还能构建哪些边?依然保持无环的状态??
input
3 2 2
1 2
2 3
1 2
1 3
output
0
input
5 3 2
5 4
2 1
4 3
4 3
1 4
output
1
2 4
input
8 1 2
1 7
2 6
1 5
output
5
5 2
2 3
3 4
4 7
6 8
节点数量在1000之内,直接考虑暴力做法
在从i到j这条边时:只需要满足左边的树没有建这条边并且右边的树也没有建边即可
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL,LL> PII;
const LL N=500200,M=2002;
LL fa1[N],fa2[N];
int find1(int x)
{
if(fa1[x]!=x) fa1[x]=find1(fa1[x]);
return fa1[x];
}
int find2(int x)
{
if(fa2[x]!=x) fa2[x]=find2(fa2[x]);
return fa2[x];
}
int main()
{
cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
LL T=1;
//cin>>T;
while(T--)
{
LL n,m1,m2;
cin>>n>>m1>>m2;
for(int i=1;i<=n;i++)
{
fa1[i]=i;
fa2[i]=i;
}
for(int i=1;i<=m1;i++)
{
int u,v;
cin>>u>>v;
int fu=find1(u),fv=find1(v);
if(fu!=fv)
{
fa1[fu]=fv;
}
}
for(int i=1;i<=m2;i++)
{
int u,v;
cin>>u>>v;
int fu=find2(u),fv=find2(v);
if(fu!=fv)
{
fa2[fu]=fv;
}
}
vector<PII> v;
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
int fi=find1(i),fj=find1(j);
if(fi==fj) continue;
int fii=find2(i),fjj=find2(j);
if(fii==fjj) continue;
v.push_back({i,j});
fa1[fi]=fj;
fa2[fii]=fjj;
}
}
cout<<v.size()<<endl;
for(int i=0;i<v.size();i++)
{
cout<<v[i].first<<" "<<v[i].second<<endl;
}
}
return 0;
}