電話列表[字典樹]
阿新 • • 發佈:2020-07-27
給出一個電話列表,如果列表中存在其中一個號碼是另一個號碼的字首這一情況,那麼就稱這個電話列表是不相容的。
假設電話列表如下:
·Emergency 911
·Alice 97 625 999
·Bob 91 12 54 26
在此例中,報警電話號碼(911)為Bob電話號碼(91 12 54 26)的字首,所以該列表不相容。
輸入格式
第一行輸入整數t,表示測試用例數量。
對於每個測試用例,第一行輸入整數n,表示電話號碼數量。
接下來n行,每行輸入一個電話號碼,號碼內數字之間無空格,電話號碼不超過10位。
輸出格式
對於每個測試用例,如果電話列表相容,則輸出”YES”。
否則,輸出”NO”。
資料範圍
1≤t≤40<?XML:NAMESPACE PREFIX = "[default] http://www.w3.org/1998/Math/MathML" NS = "http://www.w3.org/1998/Math/MathML" />1≤t≤40,
1≤n≤100001≤n≤10000
輸入樣例:
2
3
911
97625999
91125426
5
113
12340
123440
12345
98346
輸出樣例:
NO
YES
#include <iostream> #include <algorithm> #include <cstring> #include <vector> using namespace std; const int N = 1e5 + 5;//注意這個取值 int tire[N][10], tot, cnt[N]; void insert(string s, bool &flag) { if(flag == false) return; int p = 0; for(int i = 0; i < s.size(); ++ i) { int &c = tire[p][s[i] - '0']; if(!c) c = ++tot; if(cnt[p]) { flag = false; } p = c; } cnt[p] ++; } int main() { int t; cin >> t; while(t --) { int n; bool flag = true; cin >> n; vector<string> s(n); for(int i = 0; i < n; ++ i) cin >> s[i]; sort(s.begin(), s.end()); for(auto i : s) insert(i, flag); if(flag) puts("YES"); else puts("NO"); memset(cnt, 0, sizeof cnt); memset(tire, 0, sizeof tire); tot = 0; } }