【POJ】1451 T9

DFS+字典树。

  1 #include <cstdio>
  2 #include <cstring>
  3 #include <cstdlib>
  4 
  5 typedef struct Trie {
  6     int v;
  7     Trie *next[26];
  8 } Trie;
  9 
 10 Trie root;
 11 int arr[11] = {0,0,0,3,6,9,12,15,19,22,26};
 12 char buf[105], tmp[105];
 13 char map[105][105];
 14 int max[105], len;
 15 
 16 void create(char str[], int x) {
 17     int i, j, id;
 18     Trie *p = &root, *q;
 19 
 20     for (i=0; str[i]!='\0'; ++i) {
 21         id = str[i] - 'a';
 22         if (p->next[id] == NULL) {
 23             q = (Trie *)malloc(sizeof(Trie));
 24             q->v = x;
 25             for (j=0; j<26; ++j)
 26                 q->next[j] = NULL;
 27             p->next[id] = q;
 28         } else {
 29             p->next[id]->v += x;
 30         }
 31         p = p->next[id];
 32     }
 33 }
 34 
 35 void del(Trie *t) {
 36     int i;
 37 
 38     if (t == NULL)
 39         return ;
 40     for (i=0; i<26; ++i)
 41         del(t->next[i]);
 42     free(t);
 43 }
 44 
 45 void find(Trie *t, int ti, int step) {
 46     int beg = arr[buf[step]-'0'];
 47     int end = arr[buf[step]-'0'+1];
 48     int i;
 49 
 50     for (i=beg; i<end; ++i) {
 51         if (t->next[i] == NULL)
 52             continue;
 53         tmp[ti] = i+'a';
 54         if (t->next[i]->v > max[step]) {
 55             max[step] = t->next[i]->v;
 56             tmp[ti+1] = '\0';
 57             strcpy(map[step], tmp);
 58         }
 59         if (step < len-1)
 60             find(t->next[i], ti+1, step+1);
 61     }
 62 }
 63 
 64 int main() {
 65     int case_n, n, x;
 66     int i, j, t;
 67 
 68     scanf("%d", &case_n);
 69 
 70     for (t=1; t<=case_n; ++t) {
 71         for (i=0; i<26; ++i)
 72             root.next[i] = NULL;
 73         scanf("%d", &n);
 74         while (n--) {
 75             scanf("%s %d", buf, &x);
 76             create(buf, x);
 77         }
 78         scanf("%d", &n);
 79         printf("Scenario #%d:\n", t);
 80         while (n--) {
 81             scanf("%s", buf);
 82             len = strlen(buf);
 83             --len;
 84             memset(max, -1, sizeof(max));
 85             find(&root, 0, 0);
 86             for (i=0; i<len; ++i) {
 87                 if (max[i] == -1)
 88                     break;
 89                 printf("%s\n", map[i]);
 90             }
 91             for (j=i; j<len; ++j)
 92                 printf("MANUALLY\n");
 93             printf("\n");
 94         }
 95         printf("\n");
 96         del(&root);
 97     }
 98 
 99     return 0;
100 }

 

posted on 2014-06-26 16:23  Bombe  阅读(146)  评论(0编辑  收藏  举报

导航