判断两个图是否是同构的。
根据题意,这个图只能由环和链组成。判断环的个数以及每个环组成的人数,还有链的个数以及每个链组成的人数 是否相等即可。
#include <queue> #include <stack> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <limits.h> #include <string.h> #include <string> #include <algorithm> #define MID(x,y) ( ( x + y ) >> 1 ) #define L(x) ( x << 1 ) #define R(x) ( x << 1 | 1 ) #define BUG puts("here!!!") using namespace std; const int MAX = 40010; struct NODE{ int to; NODE *next;}; NODE node[MAX]; NODE *p[MAX]; int cnt; int d[MAX]; bool used[MAX]; void init() { memset(d,0,sizeof(d)); memset(used,0,sizeof(used)); memset(node,0,sizeof(node)); memset(p,0,sizeof(p)); cnt = 0; } void Add(int u,int v,int &cnt) { node[cnt].to = v; node[cnt].next = p[u]; p[u] = &node[cnt++]; } bool DFS(int t,int &cnt) { NODE *head = p[t]; while( head != NULL ) { if( used[head->to] ) { head = head->next; continue; } used[head->to] = true; cnt++; DFS( head->to ,cnt); head = head->next; } return false; } void solve(int n,int &huan,int *h,int &tree,int *t) { int cnt = 0; queue<int> q; for(int i=1; i<=n; i++) if( d[i] == 1 ) q.push(i); while( !q.empty() ) { int i = q.front(); q.pop(); if(!used[i]) { used[i] = true; cnt = 1; DFS(i,cnt); t[tree++] = cnt; } } for(int i=1; i<=n; i++) { cnt = 1; if( !used[i] ) { used[i] = true; DFS(i,cnt); h[huan++] = cnt; } } } bool check(int *a,int s1,int *b,int s2) { if( s1 != s2 ) return false; for(int i=0; i<s1; i++) if( a[i] != b[i] ) return false; return true; } int main() { int ncases,ind = 1,n,m,x,y; int h2,t2; scanf("%d",&ncases); int tt1[MAX],tt2[MAX]; int hh1[MAX],hh2[MAX]; while( ncases-- ) { init(); scanf("%d%d",&n,&m); while( m-- ) { scanf("%d%d",&x,&y); d[x]++; d[y]++; Add(x,y,cnt); Add(y,x,cnt); } int h1,t1; h1 = t1 = h2 = t2 = 0; solve(n,h1,hh1,t1,tt1); init(); scanf("%d%d",&n,&m); while( m-- ) { scanf("%d%d",&x,&y); d[x]++; d[y]++; Add(x,y,cnt); Add(y,x,cnt); } solve(n,h2,hh2,t2,tt2); sort(hh1,hh1+h1); sort(hh2,hh2+h2); sort(tt1,tt1+t1); sort(tt2,tt2+t2); printf("Case #%d: ",ind++); if( check(tt1,t1,tt2,t2) && check(hh1,h1,hh2,h2) ) printf("YES\n"); else printf("NO\n"); } return 0; }