POJ 1617 - Phone List - 字典树

xiaoxiao2021-02-28  106

链接:

  http://acm.hdu.edu.cn/showproblem.php?pid=1671


题目:

Problem Description

Given a list of phone numbers, determine if it is consistent in the sense that no number is the prefix of another. Let’s say the phone catalogue listed these numbers: 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


题意:

  给你若干个电话号码,如果存在一个号码是另一个号码的前缀,那么输出NO,否则YES。


思路:

  裸字典树。


实现:

#include <iostream> #include <algorithm> #include <set> #include <string> #include <vector> #include <queue> #include <map> #include <stack> #include <list> #include <iomanip> #include <functional> #include <sstream> #include <cstdio> #include <cstring> #include <cmath> #include <cctype> #define edl putchar('\n') #define ll long long #define clr(a,b) memset(a,b,sizeof a) #define rep(i,m,n) for(int i=m ; i<=n ; i++) #define fep(i,n) for(int i=0 ; i<n ; i++) inline int read() { int x=0;char c=getchar();while(c<'0' || c>'9')c=getchar();while(c>='0' && c<='9'){ x=x*10+c-'0';c=getchar(); }return x;} #define read read() using namespace std; struct node { node *ch[10]; bool end; node() { end = false; fep(i,10) ch[i] = NULL; } } *root; bool insert(string s) { int len = int(s.length()); node *t = root; fep(i,len) { int c = s[i] - '0'; if(t->ch[c] == NULL) t->ch[c] = new node; else if(t->ch[c]->end) return false; t = t->ch[c]; } t->end = true; return true; } void clear(node *t = root) { if(t == NULL) return ; fep(i,10) clear(t->ch[i]); delete(t); t = NULL; } int main() { #ifndef ONLINE_JUDGE freopen("in.txt","r",stdin); // printf("初始化!初始化!初始化!\n"); #endif int t = read, n; string s[10007]; while(t--) { bool flag = true; clear(); root = new node; n = read; fep(i,n) cin >> s[i]; sort(s, s+n); fep(i,n) { if(!insert(s[i])) flag = false; } if(flag) puts("YES"); else puts("NO"); } return 0; }
转载请注明原文地址: https://www.6miu.com/read-17837.html

最新回复(0)