标签:
题目链接:http://poj.org/problem?id=2503
题意:翻译单词,若在词典中找不到则输出eh。
思路:裸的字典树。
代码:
#include <iostream> #include <stdio.h> #include <string.h> #include <math.h> #include <algorithm> #include <string> #include <vector> using namespace std; #define lson l, m, rt << 1 #define rson m + 1, r, rt << 1 | 1 #define ceil(x, y) (((x) + (y) - 1) / (y)) const int SIZE = 30; const int N = 3e6 + 10; const int INF = 0x7f7f7f7f; const int MAX_WORD = 30; const int M = 1e5 + 10; struct Trie { int w; int val[SIZE]; }; int sz; Trie pn[N]; char word[M][MAX_WORD]; int newnode() { memset(pn[sz].val, 0, sizeof(pn[sz].val)); pn[sz].w = 0; return sz++; } void init() { sz = 0; newnode(); strcpy(word[0], "eh"); } void insert(char *s, int t) { int u = 0; for (int i = 0; s[i]; i++) { int idx = s[i] - 'a'; if (!pn[u].val[idx]) pn[u].val[idx] = newnode(); u = pn[u].val[idx]; } pn[u].w = t; } int findstr(char *s) { int u = 0; for (int i = 0; s[i]; i++) { int idx = s[i] - 'a'; if (!pn[u].val[idx]) return 0; u = pn[u].val[idx]; } return pn[u].w; } int main() { char s[MAX_WORD], t[MAX_WORD]; init(); int i_n = 1; while (gets(s) && s[0] != '\0') { int k = 0; bool flag = false; for (int i = 0; s[i]; i++) { if (flag) t[k++] = s[i]; if (s[i] == ' ') { s[i] = '\0'; flag = true; } } t[k] = '\0'; insert(t, i_n); strcpy(word[i_n++], s); } while (gets(s)) puts(word[findstr(s)]); return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/u014357885/article/details/47702435