[洛谷P1341]无序字母对

题目传送门

这道题实质就是欧拉路的问题。题目中有字典序的要求。注意细节即可。

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 
 6 using namespace std;
 7 
 8 #define re register
 9 #define rep(i, a, b) for (re int i = a; i <= b; ++i)
10 #define repd(i, a, b) for (re int i = a; i >= b; --i)
11 #define maxx(a, b) a = max(a, b);
12 #define minn(a, b) a = min(a, b);
13 #define LL long long
14 #define inf (1 << 30)
15 #define ERR "No Solution"
16 
17 const int maxn = 55;
18 
19 int n, e[maxn][maxn], cnt[maxn], list[maxn * maxn];
20 
21 char idc(int x) { return (x < 26 ? 'A'+x : 'a'+x-26); }
22 int idi(char x) { if (x-'A'>25) return x-'a'+26; return x-'A'; }
23 
24 void dfs(int u) {
25     rep(v, 0, 51)
26         if (e[u][v]) {
27             e[u][v] = e[v][u] = 0;
28             dfs(v);
29             list[++list[0]] = v;
30         }
31 }
32 
33 int main() {
34     scanf("%d", &n);
35 
36     rep(i, 1, n) {
37         char c[4];
38         scanf("%s", c);
39         e[idi(c[0])][idi(c[1])] = e[idi(c[1])][idi(c[0])] = 1;
40         cnt[idi(c[0])]++, cnt[idi(c[1])]++;
41     }
42 
43     int odd = 0, s = -1;
44     rep(i, 0, 55) {
45         if (cnt[i] & 1) {
46             odd++;
47             if (s == -1 || !(cnt[s] & 1))
48                 s = i;
49         }
50         if (cnt[i] && s == -1) s = i; 
51     }
52     if (odd > 2) printf(ERR);
53     else {
54         dfs(s);
55         if (list[0] != n) printf(ERR);
56         else {
57             printf("%c", idc(s));
58             repd(i, list[0], 1) printf("%c", idc(list[i]));
59         }
60     }
61 
62     return 0;
63 }

 

posted @ 2019-01-26 18:43  AC-Evil  阅读(165)  评论(0编辑  收藏  举报