http://acm.hdu.edu.cn/showproblem.php?pid=1671
题意:
判断输入的电话号码的前缀,是否是其他电话号码,如果是其他号码就输出NO,否则输出YES。解析:
这题的思路很简单,直接利用Trie树求解。
先把所有的电话号码从1到n进行标号,并插入Trie树中,然后利用Trie树查找每个电话号码,如果在查找的过程中遇到val != 0就return,判断返回的结果是不是当前的电话号码的编号,如果不是就return false。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 1000 + 10;
const int maxnode = 100005;
const int sigma_size = 26;
char str[MAXN][25];
int tot;
int ch[maxnode][sigma_size];
char val[maxnode];
struct Trie {
int sz;
Trie() {sz = 1; memset(ch[0], 0, sizeof(ch[0]));}
int idx(char c) { return c - 'a'; }
void insert(char *s) {
int u = 0, n = strlen(s);
for(int i = 0; i < n; i++) {
int c = idx(s[i]);
if(!ch[u][c]) {
memset(ch[sz], 0, sizeof(ch[sz]));
val[sz] = 0;
ch[u][c] = sz++;
}
u = ch[u][c];
val[u]++;
}
}
void query(char *s) {
int u = 0, n = strlen(s);
for(int i = 0; i < n; i++) {
putchar(s[i]);
int c = idx(s[i]);
if(val[ch[u][c]] == 1) return ;
u = ch[u][c];
}
}
};
int main() {
tot = 0;
Trie trie;
while(scanf("%s", str[tot]) != EOF) {
trie.insert(str[tot]);
tot++;
}
for(int i = 0; i < tot; i++) {
printf("%s ", str[i]);
trie.query(str[i]);
printf("\n");
}
return 0;
}