http://poj.org/problem?id=3630
题意:
给出一个电话号码列表,确定它是否一致,即没有数字是另一个的前缀。
思路:
边输入边建立字典树,通过字典树判断某个数是否是另一个的前缀很方便。
1 #include<iostream> 2 #include<algorithm> 3 #include<string> 4 #include<cstring> 5 using namespace std; 6 7 const int maxn = 100000 + 10; 8 9 char s[12]; 10 11 struct Trie 12 { 13 int ch[maxn][10]; 14 int val[maxn]; 15 int sz; 16 17 void init() 18 { 19 sz = 1; 20 memset(ch[0], 0, sizeof(ch[0])); 21 } 22 23 bool insert(char *s) 24 { 25 int u = 0, len = strlen(s); 26 int mark = 0; 27 for (int i = 0; i < len; i++) 28 { 29 int c = s[i] - '0'; 30 if (!ch[u][c]) 31 { 32 mark = 1; 33 memset(ch[sz], 0, sizeof(ch[sz])); 34 val[sz] = 0; 35 ch[u][c] = sz++; 36 } 37 u = ch[u][c]; 38 if (val[u] == 1) return false; 39 } 40 val[u] = 1; 41 if (!mark) return false; //如果到字符最后没有开辟新的结点,说明前面已经出现过该串 42 return true; 43 } 44 }t; 45 46 47 int main() 48 { 49 //freopen("D:\\txt.txt", "r", stdin); 50 int T; 51 scanf("%d", &T); 52 while (T--) 53 { 54 int n; 55 scanf("%d", &n); 56 t.init(); 57 bool flag = true; 58 while (n--) 59 { 60 scanf("%s", s); 61 if (flag && !t.insert(s)) flag = false; 62 } 63 if (flag) printf("YES\n"); 64 else printf("NO\n"); 65 } 66 return 0; 67 }