HDOJ 1671 Phone List
数据结构题
字典树
#include <stdio.h>
typedef struct _tagTrieNode {
int count;
struct _tagTrieNode *next[10];
} TrieNode,*PTrieNode;
TrieNode nodeStack[100000];
int nodeTop;
void initTrie(PTrieNode root)
{
int i;
for(i = 0;i < 10;i++)
root->next[i] = 0;
nodeTop = 0;
}
void insertTrie(PTrieNode node,char *s)
{
int i;
while(*s) {
node->next[*s - '0'] = &nodeStack[nodeTop++];
node = node->next[*s - '0'];
node->count = 1;
for(i = 0;i < 10;i++)
node->next[i] = 0;
s++;
}
node->count = 2;
return;
}
int checkTrie(PTrieNode root,char *s)
{
int i;
PTrieNode node;
node = root;
for(i = 0;s[i];i++) {
if(node->count == 2)
return 1;
if(!node->next[s[i] - '0']) {
insertTrie(node,&s[i]);
return 0;
}
node = node->next[s[i] - '0'];
}
if(node->count)
return 1;
return 0;
}
int main()
{
TrieNode TrieRoot;
char s[11];
int t,n,r;
TrieRoot.count = 0;
scanf("%d",&t);
while(t--) {
initTrie(&TrieRoot);
scanf("%d",&n);
getchar();
r = 0;
while(n--) {
gets(s);
if(r)
continue;
r = checkTrie(&TrieRoot,s);
}
puts(r ? "NO": "YES");
}
return 0;
}