题目链接。
分析:
之前做过类似的题,用的字典树链表写法,今天在训练指南上学了字典树数组的写法。
#include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <algorithm> #include <vector> using namespace std; const int maxnode = 10000*10+10; const int sigma_size = 10; struct Trie { int ch[maxnode][sigma_size]; bool val[maxnode]; int sz; int idx(char c) { return c - '0'; } void init() { sz = 1; memset(ch[0], 0, sizeof(ch[0])); } bool insert(char *s) { int u = 0, len = strlen(s); for(int i=0; i<len; i++){ int c = idx(s[i]); if(i == len-1 && ch[u][c]) return false; if(!ch[u][c]) { memset(ch[sz], 0, sizeof(ch[sz])); val[sz] = false; ch[u][c] = sz++; } u = ch[u][c]; if(val[u]) return false; } val[u] = true; return true; } }trie; int main(){ int T, n, flag; char s[15]; cin >> T; while(T--) { flag = 1; trie.init(); scanf("%d", &n); while(n--){ scanf("%s", s); if(flag){ if(!trie.insert(s)) flag = 0; } } if(flag) printf("YES\n"); else printf("NO\n"); } return 0; }
另一种写法(非字典树):
#include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <algorithm> #include <vector> using namespace std; int main(){ int T, n, flag; string s; vector<string> q; cin >> T; while(T--) { q.clear(); flag = 1; scanf("%d", &n); for(int i=0; i<n; i++) { cin >> s; q.push_back(s); } sort(q.begin(), q.end()); for(int i=0; i<n-1; i++) { if(q[i+1].find(q[i]) == 0) { flag = 0; break; } } if(flag) printf("YES\n"); else printf("NO\n"); } return 0; }