Uvaoj10054 - The Necklace

时间:2023-12-28 16:53:53

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