| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 25813 | Accepted: 7804 |
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:
- Emergency 911
- Alice 97 625 999
- 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
题目链接:点击打开链接
给出n个字符串, 问任一字符串在给定的字符串中是否存在子串, 若存在输出NO.
HDOJ1671的升级版, 直接贴代码会TLE, 发现POJ数据加强了, 暴力也会TLE, 使用静态建树的方法就可以AC.
AC代码:
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
const int MAXN = 1e5 + 10;
struct Trie
{
int cnt;
struct Trie *branch[15];
/* data */
}tel[MAXN];
int num, n;
char phone[MAXN][15];
Trie *TrieNode()
{
Trie *p = &tel[num++];
p -> cnt = 0;
for(int i = 0; i < 15; ++i)
p -> branch[i] = NULL;
return p;
}
void MakeTrie(Trie *&root, char *s)
{
int i = 0;
if(root == NULL) root = TrieNode();
Trie *p = root;
while(s[i]) {
if(!p -> branch[s[i] - '0']) p -> branch[s[i] - '0'] = TrieNode();
p = p -> branch[s[i] - '0'];
p -> cnt++;
i++;
}
}
bool judge(Trie *root, char *s)
{
int i = 0;
if(root == NULL) return true;
Trie *p = root;
while(s[i]) {
p = p -> branch[s[i] - '0'];
if(p -> cnt == 1) return false;
i++;
}
return true;
}
int main(int argc, char const *argv[])
{
int t;
scanf("%d", &t);
while(t--) {
Trie *root = NULL;
bool flag = false;
num = 0;
scanf("%d", &n);
getchar();
for(int i = 0; i < n; ++i) {
scanf("%s", phone[i]);
MakeTrie(root, phone[i]);
}
for(int i = 0; i < n; ++i)
if(judge(root, phone[i])) {
flag = true;
break;
}
if(flag) printf("NO\n");
else printf("YES\n");
}
return 0;
}

本文探讨了一种改进的算法解决方案,用于解决HDOJ1671问题的升级版。通过构建静态树来高效验证一组电话号码列表的一致性,避免了直接匹配导致的超时问题。该方法不仅适用于电话号码的检查,还能广泛应用于字符串子串存在的快速验证场景。
486

被折叠的 条评论
为什么被折叠?



