UVA-10054.The Necklace(欧拉回路)解题报告

2019-02-09-21:55:23

原题链接

题目描述:

  给定一串珠子的颜色对,每颗珠子的两端分别有颜色(用1 - 50 之间的数字表示,对每颗珠子的颜色无特殊要求),若两颗珠子的连接处为同种颜色则可以相连,

当整串珠子都满足两两可以相连时则输出连接序列,否则输出some beads may be lost。

解题思路:

  简单欧拉回路思维,注意判断该图是否可以构成欧拉回路。

算法描述及其实现:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 const int maxn = 50 + 1;
 5 const int nmax = 1000 + 1;
 6 int l, r, n, t, kase = 0;
 7 int G[maxn][maxn], ans[nmax][2], degree[maxn];
 8 bool flag;
 9 
10 void euler_circut(int i) {//当搜寻到最后一颗珠子时回溯保存之前所有的珠子。
11     for(int j = 0; j < maxn; j ++)
12         if(G[i][j]) {
13             G[i][j] --;
14             G[j][i] --;
15             euler_circut(j);
16             ans[t][0] = i + 1;
17             ans[t ++][1] = j + 1;
18         }
19 }
20 
21 int main () {
22     ios::sync_with_stdio(false);
23     int T;
24     cin >> T;
25     while(T --) {
26         flag = true;
27         memset(G, 0, sizeof(G));
28         memset(degree, 0, sizeof(degree));
29         cin >> n;
30         for(int i = 0; i < n; i ++) {
31             cin >> l >> r;
32             G[r - 1][l - 1] ++;
33             G[l - 1][r - 1] ++;
34             degree[r - 1] ++;
35             degree[l - 1] ++;
36         }
37         t = 0;
38         for(int i = 0; i < maxn; i ++)
39             if(degree[i] % 2) {
40                 flag = false;
41                 break;
42             }
43         if(flag)
44             for(int i = 0; i < maxn; i ++)
45                 euler_circut(i);
46         cout << "Case #" << ++kase << endl; 
47         if(flag)
48             for(int i = t - 1; i >= 0; i --)
49                 cout << ans[i][0] << ' ' << ans[i][1] << endl;
50         else
51             cout << "some beads may be lost" << endl;
52         cout << endl;
53     }
54     return 0;
55 }

猜你喜欢

转载自www.cnblogs.com/bianjunting/p/10358549.html