poj2503

字典樹的應用。

其實這個題可以用map很簡單的做出來,但字典樹在解決這種求解字符串匹配由於暴力求解而造成的超時的聞聽更爲明顯,所以更傾向這種方法。

#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;

struct Tree{
   int next[26];
   char english[12];
}cat[200004];
int temp;
char engl[12],fore[12];

void build(char *s,int site)
{
    if(*s)
    {
        if(!cat[site].next[*s - 'a'])
            cat[site].next[*s - 'a'] = ++ temp;
        build(s + 1,cat[site].next[*s - 'a']);
    }
    else
    strcpy(cat[site].english,engl);
}

void search(char *s,int site)
{
    if(*s)
    {
        if(!cat[site].next[*s - 'a'])
        {cout << "eh" << endl;return;}
        search(s + 1,cat[site].next[*s - 'a']);
    }
    else
    cout << cat[site].english << endl;
}

int main()
{
    char str1[100];
    while(gets(str1) && str1[0]){
        sscanf(str1,"%s %s",engl,fore);
        build(fore,0);
    }
    char str2[12];
    while((scanf("%s",str2)) != EOF)
        search(str2,0);
    return 0;
}


發佈了69 篇原創文章 · 獲贊 1 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章