A. Alien Rhyme
题意:
思路:将字符反向插入一颗Trie,然后自下而上的贪心即可,即先选后缀长的,再选后缀短的。
实现:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <iomanip> 5 6 #include <vector> 7 #include <cstring> 8 #include <string> 9 #include <queue> 10 #include <deque> 11 #include <stack> 12 #include <map> 13 #include <set> 14 15 #include <utility> 16 #include <list> 17 18 #include <cmath> 19 #include <algorithm> 20 #include <cassert> 21 #include <bitset> 22 #include <complex> 23 #include <climits> 24 #include <functional> 25 #include <unordered_set> 26 #include <unordered_map> 27 using namespace std; 28 29 typedef long long ll; 30 typedef pair<int, int> ii; 31 typedef pair<ll, ll> l4; 32 typedef pair<double, double> dd; 33 #define mp make_pair 34 #define pb push_back 35 36 #define debug(x) cerr << #x << " = " << x << " " 37 const int maxlen = 50+1; 38 const int N = 1000+1; 39 const int maxn = N * maxlen; 40 const int A = 26; 41 int g[maxn][A], cnt[maxn], tot; 42 inline int newnode() 43 { 44 memset(g[tot], 0, sizeof(g[tot])); 45 cnt[tot] = 0; 46 return tot++; 47 } 48 void init() 49 { 50 tot = 0; 51 newnode(); 52 } 53 char s[maxlen]; 54 void insert() 55 { 56 int len = strlen(s); 57 int cur = 0; 58 for (int i = len-1; i >= 0; --i) 59 { 60 int c = s[i] - 'A'; 61 if (g[cur][c] == 0) g[cur][c] = newnode(); 62 cur = g[cur][c]; 63 ++cnt[cur]; 64 } 65 } 66 int solve(int cur) 67 { 68 if (cnt[cur] == 1) return 0; 69 int ret = 0; 70 for (int c = 0; c < A; ++c) 71 if (g[cur][c]) 72 { 73 //cerr << "from " << cur << " via " << char('A'+c) << " to " << g[cur][c] << endl; 74 ret += solve(g[cur][c]); 75 } 76 int tmp = cnt[cur] - ret; 77 if (tmp >= 2) ret += 2; 78 return ret; 79 } 80 int main() 81 { 82 // ios::sync_with_stdio(false); 83 // cin.tie(0); 84 // int T; cin >> T; 85 int T; scanf("%d", &T); 86 for (int kase = 1; kase <= T; ++kase) 87 { 88 int n; scanf("%d", &n); 89 init(); 90 for (int i = 0; i < n; ++i) 91 { 92 scanf("%s", s); 93 insert(); 94 } 95 printf("Case #%d: %d\n", kase, solve(0)); 96 } 97 } 98 /* 99 1 100 10 5 5 101 101010101000010100101 102 0 2 4 6 8 13 15 18 20 103 */