HDU1671 Phone List
Phone List
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
1. Emergency 911
2. Alice 97 625 999
3. Bob 91 12 54 26
In this case, it’s not possible to call Bob, because the central would direct your call to the emergency line as soon as you had dialled the first three digits of Bob’s phone number. So this list would not be consistent. Input The first line of input gives a single integer, 1 <= t <= 40, the number of test cases. Each test case starts with n, the number of phone numbers, on a separate line, 1 <= n <= 10000. Then follows n lines with one unique phone number on each line. A phone number is a sequence of at most ten digits. Output For each test case, output “YES” if the list is consistent, or “NO” otherwise. Sample Input 2 3 911 97625999 91125426 5 113 12340 123440 12345 98346 Sample Output NO YES Source 2008 “Insigma International Cup” Zhejiang Collegiate Programming Contest - Warm Up(3) Recommend lcy | We have carefully selected several similar problems for you: 1075 1247 1800 1677 1298
Statistic | Submit | Discuss | Note
http://acm.hdu.edu.cn/showproblem.php?pid=1671
trie树做法:
1 #include2 3 using namespace std; 4 5 int n, t; 6 bool ans; 7 const int MAXN = 110000; 8 int g[MAXN][15], f[MAXN], gx, w[MAXN]; 9 10 bool add (int u, string s, int x) { 11 if (x >= s.length()) return 0; 12 w[u] = 1; 13 if (f[g[u][s[x] - '0']]) { 14 return 0; 15 } 16 else { 17 if (!g[u][s[x] - '0']) g[u][s[x] - '0'] = ++gx; 18 if (x == s.length() - 1) { 19 if (w[g[u][s[x] - '0']]) return 0; 20 f[g[u][s[x] - '0']] = 1; 21 w[g[u][s[x] - '0']] = 1; 22 return 1; 23 } 24 else { 25 return add(g[u][s[x] - '0'], s, x + 1); 26 } 27 } 28 } 29 30 int main() { 31 cin >> t; 32 while (t--) { 33 ans = 1; 34 cin >> n; 35 memset(f, 0, sizeof(f)); 36 memset(g, 0, sizeof(g)); 37 memset(w, 0, sizeof(w)); 38 gx = 1; 39 while (n--) { 40 string s; 41 cin >> s; 42 ans = min(ans, add(1, s, 0)); 43 } 44 if (ans) { 45 cout << "YES\n"; 46 } 47 else { 48 cout << "NO\n"; 49 } 50 } 51 return 0; 52 }
排序,每对相邻的暴力验证一下:
1 #include2 3 using namespace std; 4 5 string s[10001]; 6 7 int main() { 8 int t; 9 cin >> t; 10 while (t--) { 11 int n; 12 cin >> n; 13 for (int i = 1; i <= n; ++i) cin >> s[i]; 14 sort(s + 1, s + 1 + n); 15 bool tf = 1; 16 for (int i = 2; i <= n && tf; ++i) { 17 if (s[i].length() > s[i - 1].length()) { 18 bool x = 1; 19 for (int j = 0; j < s[i - 1].length(); ++j) { 20 if (s[i - 1][j] != s[i][j]) { 21 x = 0; 22 break; 23 } 24 } 25 if (x) tf = 0; 26 } 27 } 28 if (tf) cout << "YES\n"; 29 else cout << "NO\n"; 30 } 31 return 0; 32 }