珠子有范围,先用max,min记录其最大最小值,后来在dfs下才能限定范围,而不总是在1到50里搜索。这样做,总是好的。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define INF 1<<30
const int maxn=60;
int p[maxn],dgr[maxn],G[maxn][maxn],max,min;
void dfs(int u)
{
for(int v=1;v<=max;v++)
if(G[u][v])
{
G[u][v]--;
G[v][u]--;
dfs(v);
printf("%d %d\n",v,u);
}
}
int find(int x)
{
return p[x]==x? x:(p[x]=find(p[x]));
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("10054.txt","r",stdin);
//freopen("10054.1.txt","r",stdin);
#endif
int t;
scanf("%d",&t);
for(int i=1;i<=t;i++)
{
max=0;min=INF;
if(i!=1) printf("\n");
printf("Case #%d\n",i);
int n;
scanf("%d",&n);
//if(!n) continue;
memset(dgr,0,sizeof(dgr));
memset(G,0,sizeof(G));
int j;
for(j=1;j<=50;j++) p[j]=j;
for(j=0;j<n;j++)
{
int x,y;
scanf("%d%d",&x,&y);
if(max<x) max=x;
if(max<y) max=y;
if(min>x) min=x;
if(min>y) min=y;
dgr[x]++;
dgr[y]++;
G[x][y]++;
G[y][x]++;
x=find(x);
y=find(y);
if(x!=y) p[x]=y;
}
int t=find(min);
bool ok=1;
for(j=min+1;j<=max;j++)
if(dgr[j] && t!=find(j))
{
ok=0;
break;
}
if(ok)
for(j=min;j<=max;j++)
if(dgr[j]%2)
{
ok=0;
break;
}
if(ok) dfs(min);
else printf("some beads may be lost\n");
}
return 0;
}