较简单字典树,每输入一对字符串,前一个放在字典(数组)中,后一个插入字典树中,并将其最终的flag赋为前一个在数组中的下标,再就好找了。输入的处理方法要注意一下。
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <string> #include <cstdlib> #include <sstream> using namespace std; #define N 100027 struct node { int flag; node *next[26]; }*root; char dic[N][11]; node *create() { node *p; p = (node *)malloc(sizeof(node)); for(int i=0;i<26;i++) p->next[i] = NULL; return p; } void insert(char *ss,int x) { int i = 0,k; node *p = root; while(ss[i]) { k = ss[i++] - 'a'; if(p->next[k] == NULL) p->next[k] = create(); p = p->next[k]; } p->flag = x; } void release(node *p) { for(int i=0;i<26;i++) { if(p->next[i] != NULL) release(p->next[i]); } free(p); } int search(char *ss) { node *p = root; int i = 0,k; while(ss[i]) { k = ss[i++] - 'a'; if(p->next[k] == NULL) return -1; p = p->next[k]; } return p->flag; } int main() { int k,i; char ss[31],sa[11]; k = 0; root = create(); while(gets(ss) && strlen(ss)) { sscanf(ss,"%s %s",dic[k],sa); insert(sa,k++); } while(scanf("%s",sa)!=EOF) { i = search(sa); if(i != -1) printf("%s ",dic[i]); else puts("eh"); } release(root); return 0; }