HDU 1075 What Are You Talking About

字典树……

#include <cstdio> 
#include <cstring>
using namespace std;
struct node{int son[26]; char hash[12];}trie[1000000];
int cnt,n;
char s[100000],s1[12],ans[12];
void insert(char *s,char *s1){
    for(int l=strlen(s),x=0,i=0;i<l;i++){
        if(!trie[x].son[s[i]-'a'])trie[x].son[s[i]-'a']=++cnt;
        x=trie[x].son[s[i]-'a'];
        if(i==l-1)strcpy(trie[x].hash,s1);
    }
}
int find(char *s){
    for(int l=strlen(s),x=0,i=0;i<l;i++){
        if(!trie[x].son[s[i]-'a'])return 0;
        x=trie[x].son[s[i]-'a'];
        if(i==l-1){
            strcpy(ans,trie[x].hash);
            return strlen(ans)?1:0;
        }
    }
}
int main(){
    while(~scanf("%s",&s)){
        if(strcmp(s,"START")==0)continue;
        if(strcmp(s,"END")==0)break;
        scanf("%s",&s1);
        insert(s1,s);
    }
    gets(s);
    while(gets(s)){
        if(strcmp(s,"START")==0)continue;
        if(strcmp(s,"END")==0)break;
        int i=0,j=0,len=strlen(s); 
        while(i<len){
            if(s[i]<'a'||s[i]>'z'){
                if(find(s1))printf("%s",ans);
                else printf("%s",s1);
                printf("%c",s[i++]);
                j=0;
                memset(s1,0,sizeof s1);
                memset(ans,0,sizeof ans);
            }else s1[j++]=s[i++];
        }
        printf("\n");
    }
    return 0;
}

posted @ 2014-02-19 20:23  forever97  阅读(186)  评论(0编辑  收藏  举报