uva 10054 The necklacr
题意:输入T表示T组数据,每组数据先输入n,表示有n个珠子,每个珠子有2个颜色,用1-50的数字来代替,颜色相同可以连接起来 问珠子能不能串成一个环
思路:以每一个颜色作为一个结点 然后转化成求欧拉回路 先用并查集判断是否存在欧拉回路,存在的话dfs输出欧拉路径
AC代码:
1 #include "iostream" 2 #include "string.h" 3 #include "stack" 4 #include "queue" 5 #include "string" 6 #include "vector" 7 #include "set" 8 #include "map" 9 #include "algorithm" 10 #include "stdio.h" 11 #include "math.h" 12 #define ll long long 13 #define ull unsigned ll 14 #define lson l,mid,rt<<1 15 #define rson mid+1,r,rt<<1|1- 16 #define len (Tr[rt].r-Tr[rt].l+1) 17 #define mem(a) memset(a,0,sizeof(a)) 18 #define bug cout<<"UUUUUUUUUUUUU\n"; 19 using namespace std; 20 int M[55][55],d[2005],pre[2005],l0,f,tot; 21 int mm; 22 void Dfs(int k,int l,int p){ 23 for(int i=1; i<=mm; ++i){ 24 if(M[k][i]){ 25 M[k][i]--,M[i][k]--; 26 Dfs(i,l+1,p+1);cout<<i<<" "<<k<<endl; 27 } 28 } 29 } 30 int finds(int x){ 31 int k, j, r; 32 r = x; 33 while(r != pre[r]) r = pre[r]; 34 k = x; 35 while(k != r){ 36 j = pre[k]; 37 pre[k] = r; 38 k = j; 39 } 40 return r; 41 } 42 void makeset(int x,int y){ 43 int fx = finds(x), fy = finds(y); 44 pre[fx] = fy; 45 } 46 int main(){ 47 int T,T0=1,n,u,v,s[100]; 48 scanf("%d",&T); 49 while(T--){ 50 mem(M),mem(d),mem(s); 51 if(T0!=1)printf("\n"); 52 scanf("%d",&n); l0=n,mm=0; 53 for(int i=1; i<=55; ++i) pre[i]=i; 54 for(int i=0; i<n; ++i){ 55 scanf("%d%d",&u,&v); 56 M[u][v]++,M[v][u]++; 57 makeset(u,v); 58 s[u]=1,s[v]=1; 59 mm=max(mm,u),mm=max(mm,v); 60 } 61 printf("Case #%d\n",T0++); 62 f=1;int f0=finds(mm); 63 for(int i=1; i<=mm; ++i){ 64 int kk=0; 65 for(int j=1; j<=mm; ++j) kk+=M[i][j]; 66 if(kk&1){ 67 f=0; 68 break; 69 } 70 } 71 for(int i=1; i<=mm; ++i){ 72 if(s[i]&&finds(i)!=f0){ 73 f=0; 74 break; 75 } 76 } 77 d[0]=mm; 78 if(!f) printf("some beads may be lost\n"); 79 else Dfs(mm,0,1); 80 } 81 return 0; 82 }