Uvaoj10054 - The Necklace

Uvaoj10054 - The Necklace



/*
    题意:打印欧拉回路!
    思路:开始时不明白,dfs为什么是后序遍历? 
    因为欧拉回路本身是一条回路,那么我们在dfs时,可能存在提前找到回路,这条回路可能不是欧拉回路,
    因为没有遍历完成所有的边!如果写成前序遍历的话,存储起来的路径就不是一条完整的路径了!它有可能
    是多条回路组成的!答案就是错误 的!如果是后序遍历的话,当dfs是遇到了回路,那么就退出当前栈的搜索!
    去寻找其他的路径!最终得到的只有一条回路路径!-->欧拉回路~! 
*/ 
#include<iostream>
#include<cstring>
#define M 55
#define Max 0x3f3f3f3f
using namespace std;

int cnt[M][M];
int deg[M];
int map[M][M];
int x;

struct Point{
   int x, y;
   Point(){}
   
   Point(int x, int y){
      this->x=x;
      this->y=y; 
   }
}; 

Point p[1005];
int top;

void dfs(int u){
   if(!deg[u]) return;
   for(int i=1; i<=50; ++i)
     if(map[u][i] && cnt[u][i]){
         --cnt[u][i];
         --cnt[i][u];
         --deg[u];
         --deg[i];
         dfs(i);
         p[++top]=Point(u, i); 
     } 
}

int main(){
   int t, n, k=0;
   cin>>t;
   while(t--){
      cin>>n;
      x=Max;
      memset(cnt, 0, sizeof(cnt));
      memset(map, 0, sizeof(map));
      memset(deg, 0, sizeof(deg));
      for(int i=1; i<=n; ++i){
          int u, v;
          cin>>u>>v;
          deg[u]++;
          deg[v]++;
          map[u][v]=1;
          map[v][u]=1;
          cnt[u][v]++;
          cnt[v][u]++;
          if(x>u) x=u;
          if(x>v) x=v;
      }
      int ok=0;
      for(int i=1; i<=50; ++i)
         if(deg[i]%2!=0){
            ok=1;
            break;
         }
      cout<<"Case #"<<++k<<endl;
      if(ok){
         cout<<"some beads may be lost"<<endl;
         if(t) cout<<endl;
         continue;
      }
      top=0;
      dfs(x);
      if(top==n){
         for(top; top>=1; --top)
            cout<<p[top].x<<" "<<p[top].y<<endl;
      }
      else cout<<"some beads may be lost"<<endl;      
      if(t) cout<<endl; 
   }
   return 0;
}