hdu 1075 What Are You Talking About (字典樹)

題目鏈接:   hdu 1075

題目大意:   類似解密過程,右邊是單詞對應的密文

                  給出一串字符,可以解密的單詞都翻譯出來

解題思路:   將明文存進數組,然後將密文建成Trie樹

                  將最後結點存進樹時順便記錄它明文的下標

                  搜索密文的每一個單詞,若在樹中則翻譯出來

代碼:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100000
struct snode{
    int next[27];    //第一種寫法
    int w;
}Tree[MAX*10];
char ch1[MAX*11][11],ch2[11];
int Index;
void Insert(int k,int Tlen)     //遍歷插入字典樹
{
    int i,S=0,child;
    for(i=1;i<=Tlen;i++)
    {
        child=ch2[i-1]-'a'+1;
        if(Tree[S].next[child]==0)
        {
            if(i==Tlen)
                Tree[Index].w=k;
            Tree[S].next[child]=Index++;
        }
        else
        {
            if(i==Tlen)
                Tree[Tree[S].next[child]].w=k;
        }
        S=Tree[S].next[child];
    }
}

int Query(char ch5[],int Tlen)   //遍歷查詢字典樹
{
    int i,S=0,child;
    for(i=1;i<=Tlen;i++)
    {
        child=ch5[i-1]-'a'+1;
        if(Tree[S].next[child]!=0)
        {
            if(i==Tlen&&Tree[Tree[S].next[child]].w!=0)
            {
                printf("%s",ch1[Tree[Tree[S].next[child]].w]);
                 return 1;
            }
            S=Tree[S].next[child];
        }
        else
            return 0;
    }
    return 0;
}

int main()
{
    int n=1,i,j;
    char ch3[10000],ch4[20];
    Index=1;
    memset(Tree,0,sizeof(Tree));
    scanf("%s",ch3);
    while(scanf("%s",ch1[n]))
    {
        if(strcmp(ch1[n],"END")==0)
            break;
        scanf("%s",ch2);
        Insert(n,strlen(ch2));
        n++;
    }
    scanf("%s",ch3);
    getchar();
    while(gets(ch3))
    {
        if(strcmp(ch3,"END")==0)
        {
            break;
        }
        for(i=0,j=0;ch3[i]!='\0';i++)
        {
            if(ch3[i]<'a'||ch3[i]>'z')  //枚舉每個單詞是否存在翻譯
            {
                if(Query(ch4,j)==0)
                {
                    printf("%s",ch4);
                }
                printf("%c",ch3[i]);
                ch4[0]='\0';           //不存在初始化繼續枚舉下一個
                j=0;
            }
            else
            {
                ch4[j++]=ch3[i];
                ch4[j]='\0';
            }
        }
        if(ch4[0]!='\0')               //***最後一個單詞
        {
            if(Query(ch4,j)==0)
                printf("%s",ch4);
        }
        puts("");
    }
    return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章