hdu 1671(字典树)

 1 /*

 2 *  字典树 

 3 */

 4 #include <cstdio>

 5 #include <cstring>

 6 #include <cstdlib>

 7 #include <iostream>

 8 

 9 using namespace std;

10 

11 const int N = 11;

12 

13 bool yes;

14 char str[N];

15 struct node {

16     bool flag;

17     node *child[10];

18     node() {

19         flag = false;

20         for (int i=0; i<10; ++i) child[i] = NULL;

21     }

22 }*root;

23 

24 void insert(char str[]) {

25     node *p = root;

26     int len = strlen(str);

27     for (int k,i=0; i<len; ++i, p=p->child[k]) {

28         k = str[i] - '0';

29         if (!p->child[k]) p->child[k] = new node();

30         else if (i == len-1) {yes = false; return;}

31         if (p->child[k]->flag) {yes = false; return;}

32     }

33     p->flag = true;

34 }

35 

36 void del(node *p) {//释放内存 

37     for (int i=0; i<10; ++i) {

38         if (p->child[i]) del(p->child[i]);

39     }

40     delete p;

41     p = NULL;

42 }

43 

44 int main() {

45     int t;

46     scanf ("%d", &t);

47     while (t--) {

48         int n;

49         scanf ("%d", &n);

50         yes = true;

51         root = new node();

52         while (n--) {

53             scanf ("%s", str);

54             if (yes) insert(str);

55         }

56         if (yes) puts("YES");

57         else puts("NO");

58         del(root);

59     }

60     return 0;

61 }

 

你可能感兴趣的:(HDU)