HDU 3926 Hand in Hand(同构图)

Hand in Hand

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 122768/62768 K (Java/Others)
Total Submission(s): 2600    Accepted Submission(s): 884


Problem Description
In order to get rid of Conan, Kaitou KID disguises himself as a teacher in the kindergarten. He knows kids love games and works out a new game called "hand in hand". 

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?" 
 

Input
The first line contains a single positive integer T( T <= 100 ), indicating the number of datasets.
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.
 

Output
For each test case: output the case number as shown and "YES" if the two graph are isomorphism or "NO" otherwise.
 

Sample Input
 
   
2
3 2
1 2
2 3
3 2
3 2
2 1
3 3
1 2
2 3
3 1
3 1
1 2
 

Sample Output
 
   
Case #1: YES
Case #2: NO

这道题每个节点的度不会超过2,图的联通分量非链即环,直接比较这些链或环是否相同,

思路:
1.该题形成的图有多个连通分量,非链即环,且每个点的度不得大于2
2.基本的Find,merge不变,把合并好后的所有点进行排序(点的子结点数优先,从小到大排列,若子节点数相等,则链在前)
3.把两个图排序后一一比较两个点,若有一个不同,则不同构。

#include
#include
#include
using namespace std;
int f[10005];
struct node{
	int num;//节点数 
	bool ring;//是否存在环 
};
node g1[10005],g2[10005];
int cmp(node a,node b)//结构体排序 
{
	if(a.num==b.num) return a.ring < b.ring ;
	else return a.num  g[fy].num )//为了使每个连通分量的根节点一致 
		{
			f[fy]=fx;
			g[fx].num +=g[fy].num; 
		}
		else
		{
			f[fx]=fy;
			g[fy].num +=g[fx].num;
		}
	}
	return;
}
int judge(int n,int x,node *g1,node *g2)//判断是否同构 
{
	int flag=0;
	sort(g1+1,g1+n+1,cmp);
	sort(g2+1,g2+x+1,cmp);
	for(int i=1;i<=n;i++)
	{
		if(g1[i].num !=g2[i].num||(g1[i].num ==g2[i].num&&g1[i].ring!=g2[i].ring))
		{
			flag=1;
			break;
		}
	}
	if(flag==1) return 0;//否 
	else return 1;//是 
}
int main()
{
	int t,ca=0;
	scanf("%d",&t);
	while(t--)
	{
		int x,y,n,m;
		scanf("%d%d",&n,&m);
		init(n,g1);
		for(int i=0;i

你可能感兴趣的:(图论)