zoukankan      html  css  js  c++  java
  • 【POJ】2503 Babelfish

    字典树简单题。

     1 #include <cstdio>
     2 #include <cstring>
     3 #include <cstdlib>
     4 
     5 typedef struct Trie {
     6     Trie *next[26];
     7     char str[15];
     8 } Trie;
     9 
    10 Trie root;
    11 
    12 void create(char str[], char des[]) {
    13     int i = 0, j, id;
    14     Trie *p = &root, *q;
    15 
    16     while (str[i]) {
    17         id = str[i] - 'a';
    18         if (p->next[id] == NULL) {
    19             q = (Trie *)malloc(sizeof(Trie));
    20             for (j=0; j<26; ++j)
    21                 q->next[j] = NULL;
    22             p->next[id] = q;
    23         }
    24         p = p->next[id];
    25         ++i;
    26     }
    27     strcpy(p->str, des);
    28 }
    29 
    30 void find(char str[]) {
    31     int i = 0, id;
    32     Trie *p = &root;
    33 
    34     while (str[i]) {
    35         id = str[i] - 'a';
    36         if (p->next[id] == NULL) {
    37             printf("eh
    ");
    38             return ;
    39         }
    40         p = p->next[id];
    41         ++i;
    42     }
    43     printf("%s
    ", p->str);
    44 }
    45 
    46 void del(Trie *t) {
    47     int i;
    48     if (t == NULL)
    49         return ;
    50     for (i=0; i<26; ++i)
    51         del(t->next[i]);
    52     free(t);
    53 }
    54 
    55 int main() {
    56     char src[12], des[25];
    57     char *p;
    58 
    59     for (int i=0; i<26; ++i)
    60         root.next[i] = NULL;
    61 
    62     while (gets(des)!=NULL && des[0]!='') {
    63         p = strchr(des, ' ');
    64         strcpy(src, p+1);
    65         *p = '';
    66         create(src, des);
    67     }
    68 
    69     while (scanf("%s", src) != EOF)
    70         find(src);
    71 
    72     return 0;
    73 }
  • 相关阅读:
    215. Kth Largest Element in an Array
    214. Shortest Palindrome
    213. House Robber II
    212. Word Search II
    210 Course ScheduleII
    209. Minimum Size Subarray Sum
    208. Implement Trie (Prefix Tree)
    207. Course Schedule
    206. Reverse Linked List
    sql 开发经验
  • 原文地址:https://www.cnblogs.com/bombe1013/p/3810815.html
Copyright © 2011-2022 走看看