hdu 1671
Trie树,题目不难,但还是WA了一次,没有考虑后输入的字符串是前输入的字符串的前缀的情况,真是太粗心了。不过做了几道Trie树的题目以后,代码写得还是比较通用了,慢慢再改进吧
/*
* hdu1671/win.c
* Created on: 2011-8-19
* Author : ben
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define CHAR_NUM 10
#define BASE '0'
typedef struct Trie {
unsigned char isaend;
struct Trie * br[CHAR_NUM];
} Trie;
int flag;
Trie* newTrieNode() {
int i;
Trie* node = (Trie *) malloc(sizeof(Trie));
for (i = 0; i < CHAR_NUM; i++) {
node->br[i] = NULL;
}
node->isaend = 0;
return node;
}
void insert(Trie *root, char *str, int len) {
int i;
if (root->isaend) {
flag = 0;
}
if (len <= 0) {
root->isaend = 1;
for (i = 0; i < CHAR_NUM; i++) {
if(root->br[i]) {
flag = 0;
return ;
}
}
return;
}
i = (*str) - BASE;
if (!root->br[i]) {
root->br[i] = newTrieNode();
}
insert(root->br[i], str + 1, len - 1);
}
void destroy(Trie *root) {
int i;
for (i = 0; i < CHAR_NUM; i++) {
if (root->br[i] != NULL) {
destroy(root->br[i]);
}
}
free(root);
}
void work() {
Trie *root = newTrieNode();
int n;
char str[100];
scanf("%d", &n);
flag = 1;
while (n--) {
scanf("%s", str);
insert(root, str, strlen(str));
}
if (flag) {
puts("YES");
} else {
puts("NO");
}
destroy(root);
}
int main() {
#ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
#endif
int T;
scanf("%d", &T);
while (T--) {
work();
}
return 0;
}