Initially kids run on the playground randomly. When Kid says "stop", kids catch others' hands immediately. One hand can catch any other hand randomly. It's weird to have more than two hands get together so one hand grabs at most one other hand. After kids stop moving they form a graph.
Everybody takes a look at the graph and repeat the above steps again to form another graph. Now Kid has a question for his kids: "Are the two graph isomorphism?"
There are two graphs in each case, for each graph:
first line contains N( 1 <= N <= 10^4 ) and M indicating the number of kids and connections.
the next M lines each have two integers u and v indicating kid u and v are "hand in hand".
You can assume each kid only has two hands.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <set>
#include <algorithm>
#include <queue>
#include <stack>
#define MAXN 30005
#define MAX 10005
#define INF 0x3f3f3f3f
using namespace std;
int Father[MAX];
struct graph
{
int num;//節點數
bool ring;//是否是環
};
graph g1[MAX],g2[MAX];
int p,q,t,cnt,n1,m1,n2,m2,flag;
bool cmp1(const graph &a, const graph &b)//結點小的優先,鏈表優先
{
if(a.num < b.num)
{
return true;
}
if(a.num == b.num && a.ring < b.ring)
{
return true;
}
return false;
}
int Find(int x)
{
return x == Father[x]?Father[x]:Find(Father[x]);
}
void Merge(int x,int y,graph *g)
{
int ix = Find(x);
int iy = Find(y);
if(ix == iy)
{
g[ix].ring = true;
}
else
{
if(g[ix].num > g[iy].num)
{
Father[iy] = ix;
g[ix].num += g[iy].num;
}
else
{
Father[ix] = iy;
g[iy].num += g[ix].num;
}
}
}
int cmp2(graph *g1, graph *g2,int len1,int len2)
{
sort(g1+1,g1+1+len1,cmp1);
sort(g2+1,g2+1+len2,cmp1);
for (int i = 1; i <= len2; i++)
{
if(g1[i].num != g2[i].num || (g1[i].num == g2[i].num &&g1[i].ring !=g2[i].ring))
{
return 0;
}
}
return 1;
}
void Unit(int n, int m, graph *g)
{
for(int i = 1; i <= n; i++)
{
Father[i] = i;
g[i].num = 1;
g[i].ring = false;
}
}
int main()
{
scanf("%d",&t);
while (t--)
{
cnt++;
flag = 0;
scanf("%d%d",&n1,&m1);
Unit(n1,m1,g1);
for (int i = 0; i < m1;i++)
{
scanf("%d%d",&p,&q);
Merge(p,q,g1);
}
scanf("%d%d",&n2,&m2);
Unit(n2,m2,g2);
for (int i = 0; i < m2;i++)
{
scanf("%d%d",&p,&q);
Merge(p,q,g2);
}
flag = cmp2(g1,g2,n1,n2);
printf("Case #%d: ",cnt);
if(flag)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
return 0;
}