hdu 1247 trie樹入門題

題目:http://acm.hdu.edu.cn/showproblem.php?pid=1247

題意:給你一些單詞,輸出是由兩個其他的單詞組成的單詞。

分析:trie樹的入門題,很簡單,這題的數據很水,每個單詞的長度不會超過26.

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int N=50005;
char word[N][27];
struct node
{
    bool ok;
    node *next[26];
    node()
    {
        ok=false;
        memset(next,0,sizeof(next));
    }
};
void Insert(node *rt,char *s)
{
    int i=0;
    node *p=rt;
    while(s[i]){
        int k=s[i++]-'a';
        if(p->next[k]==NULL)
            p->next[k]=new node();
        p=p->next[k];
    }
    p->ok=true;
}
bool Search(node *rt,char s[])
{
    int i=0,top=0,sta[27];
    node *p=rt;
    while(s[i]){
        int k=s[i++]-'a';
        if(p->next[k]==NULL)return 0;
        p=p->next[k];
        if(p->ok&&s[i])sta[top++]=i;
    }
    while(top){
        bool flag=1;
        i=sta[--top];
        p=rt;
        while(s[i]){
            int k=s[i++]-'a';
            if(p->next[k]==NULL){
                flag=0;break;
            }
            p=p->next[k];
        }
        if(flag&&p->ok)return true;
    }
    return 0;
}
int main()
{
    int n=0;
    //freopen("f.txt","r",stdin);
    node *rt=new node();
    while(gets(word[n])){
        Insert(rt,word[n]);
        n++;
    }
    for(int i=0;i<n;i++){
        if(Search(rt,word[i]))
            printf("%s\n",word[i]);
    }
    return 0;
}

這題用map的話也可以,每次把一個單詞分成兩部分,分別用map判斷是否兩部分存在。時間複雜度n*(單詞長度)*n(logn),有點大,但是數據比較弱,隨便水水還是可以的。

#include<iostream>
#include<cstdio>
#include<map>
#include<string>
using namespace std;
map<string,bool>a;
string s[50005];
int main()
{
    int t=0;
    //freopen("f.txt","r",stdin);
    while(cin>>s[t]){
        a[s[t]]=true;
        t++;
    }
    for(int i=0;i<t;i++){
        int n=s[i].size();
        for(int j=1;j<n;j++){
            string s1(s[i],0,j);
            string s2(s[i],j);
            if(a[s1]&&a[s2]){
                cout<<s[i]<<endl;break;
            }
        }
    }
    return 0;
}




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