CF #738 (Div. 2)D1. Mocha and Diana (Easy Version)

 看了其他博主的思路,借鉴的

This is the easy version of the problem. The only difference between the two versions is the constraint on nn. You can make hacks only if all versions of the problem are solved.

A forest is an undirected graph without cycles (not necessarily connected).

Mocha and Diana are friends in Zhijiang, both of them have a forest with nodes numbered from 11 to nn, and they would like to add edges to their forests such that:

  • After adding edges, both of their graphs are still forests.
  • They add the same edges. That is, if an edge (u,v)(u,v) is added to Mocha's forest, then an edge (u,v)(u,v) is added to Diana's forest, and vice versa.

Mocha and Diana want to know the maximum number of edges they can add, and which edges to add.

Input

The first line contains three integers nn, m1m1 and m2m2 (1≤n≤10001≤n≤1000, 0≤m1,m2

Each of the next m1m1 lines contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) — the edges in Mocha's forest.

Each of the next m2m2 lines contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) — the edges in Diana's forest.

Output

The first line contains only one integer hh, the maximum number of edges Mocha and Diana can add (in each forest).

Each of the next hh lines contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) — the edge you add each time.

If there are multiple correct answers, you can print any one of them.

#include
using namespace std;
const int maxx=1010;
int vis[maxx-5],vis1[maxx-5];
void init(int n){for(int i=0;i<=n;i++)vis[i]=i;}
void init1(int n){for(int i=0;i<=n;i++)vis1[i]=i;}
int find(int x){return vis[x]==x?vis[x]:vis[x]= find(vis[x]);}
int find1(int x){return vis1[x]==x?vis1[x]:vis1[x]= find1(vis1[x]);}
int meege(int x,int y){
    int tx=find(x), ty=find(y);
    if(tx!=ty)vis[ty]=tx;
}
int meege1(int x,int y){
    int tx=find1(x),ty=find1(y);
    if(tx!=ty)vis1[ty]=x;
}
int main(){
    //这题只要输出一种就可以了- -没必要看着样例打- -,我们可以弄俩个并查集把俩个情况分开,然后暴力跑把他链接,中间记录下
    int t,n,m,c=1,c1=1;
    cin>>t>>n>>m;
    init(t), init1(t);
    for(int i=1;i<=n;i++){
        int x,y;
        cin>>x>>y;
        if(find(x)!= find(y)){
            meege(x,y);
            c++;
        }
    }
    for(int i=1;i<=m;i++){
        int x,y;
        cin>>x>>y;
        if(find1(x)!= find1(y)){
            meege1(x,y);
            c1++;
        }
    }
    if(c==t||c1==t){
        cout<<0<>ans;
        for(int i=1;i<=t;i++){
            for(int j=1;j<=t;j++){
                if(i==j)continue;
                int tx= find(i),ty= find(j);
                int tx1= find1(i),ty1= find1(j);
                if(tx!=ty&&tx1!=ty1){
                    meege(tx,ty);
                    meege1(tx1,ty1);
                    c++,c1++;
                    ans.push_back({i,j});
                    if(c==t||c1==t)break;
                }
            }
            if(c==t||c1==t)break;
        }
        cout<

你可能感兴趣的:(算法,c++)