【题目链接】
http://poj.org/problem?id=3630
【算法】
字典树
【代码】
#include <algorithm> #include <bitset> #include <cctype> #include <cerrno> #include <clocale> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <exception> #include <fstream> #include <functional> #include <limits> #include <list> #include <map> #include <iomanip> #include <ios> #include <iosfwd> #include <iostream> #include <istream> #include <ostream> #include <queue> #include <set> #include <sstream> #include <stdexcept> #include <streambuf> #include <string> #include <utility> #include <vector> #include <cwchar> #include <cwctype> #include <stack> #include <limits.h> using namespace std; #define MAXN 10010 int i,TC,n; bool flag; char s[MAXN][10]; struct info { int child[10]; bool is_last; }; class Trie { private : int tot; info a[MAXN*10]; public : inline void clear(int x) { int i; a[x].is_last = false; for (i = 0; i < 10; i++) { if (a[x].child[i]) { tot--; clear(a[x].child[i]); a[x].child[i] = 0; } } } inline bool insert(char *s) { int i,x = 0,len; bool flag = false; len = strlen(s); for (i = 0; i < len; i++) { if (a[x].child[s[i]-'0']) { x = a[x].child[s[i]-'0']; if (a[x].is_last || i == len - 1) flag = true; } else { a[x].child[s[i]-'0'] = ++tot; x = a[x].child[s[i]-'0']; } } a[x].is_last = true; return flag ^ 1; } } T; int main() { scanf("%d",&TC); while (TC--) { flag = true; T.clear(0); scanf("%d",&n); for (i = 1; i <= n; i++) scanf("%s",&s[i]); for (i = 1; i <= n; i++) { if (T.insert(s[i])) continue; else { flag = false; break; } } if (flag) printf("YES "); else printf("NO "); } return 0; }