-
Notifications
You must be signed in to change notification settings - Fork 0
/
10054.cpp
131 lines (127 loc) · 1.96 KB
/
10054.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/*
10054 - The Necklace
*/
#include<bits/stdc++.h>
using namespace std;
const int MX = 55;
int parent[MX];
int degree[MX];
int graph[MX][MX];
int n;
///initialize
void init()
{
memset(degree,0,sizeof(degree));
memset(graph,0,sizeof(graph));
for(int i=0; i<MX; i++)
{
parent[i]=i;
}
}
///find parent
int find_parent(int x)
{
if(x!=parent[x])
{
parent[x] = find_parent(parent[x]);
}
return parent[x];
}
///checking whether all degree's are even
/// and the graph is connected
bool isok()
{
int root = -1;
for(int i=0; i<MX ; i++)
{
if(degree[i]&1)
return false;
if(degree[i])
{
if(root == -1)
root = find_parent(i);
else
{
if(root != find_parent(i))
return false;
}
}
}
return true;
}
///printing euler path
void dfs(int cur)
{
for(int i=1; i<MX; i++)
{
if(graph[cur][i])
{
graph[cur][i]--;
graph[i][cur]--;
dfs(i);
printf("%d %d\n",i,cur);
}
}
}
int main()
{
int cas=1,t,x,y,start;
bool isfirst = true;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
init();
for(int i=0; i<n; i++)
{
scanf("%d %d",&x,&y);
start = x;
graph[x][y]++;
graph[y][x]++;
degree[x]++;
degree[y]++;
parent[find_parent(x)]=find_parent(y);
}
if(isfirst)
isfirst=false;
else
{
printf("\n");
}
printf("Case #%d\n",cas++);
if(!isok())
{
printf("some beads may be lost\n");
}
else
{
dfs(start);
}
}
return 0;
}
/*
Sample Input
2
5
1 2
2 3
3 4
4 5
5 6
5
2 1
2 2
3 4
3 1
2 4
Sample Output
Case #1
some beads may be lost
Case #2
2 1
1 3
3 4
4 2
2 2
*/