hdoj1247(字典树)

题目链接:https://vjudge.net/problem/HDU-1247

题意:给定n个字符串(n<=50000),判断其中哪些字符串恰能由另外两个不同的字符串连接而成。

思路:

  暴力字典树即可。右n个字符串建树,然后把每个字符串拆分判断两部分是否都在树中。

AC code:

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

const int maxn=50005;
const int maxm=1e6+5;
int n,trie[maxm][30],key[maxm],cnt;
char str[maxn][30];

void insert(char *s){
    int len=strlen(s),u=0;
    for(int i=0;i<len;++i){
        int t=s[i]-'a';
        if(!trie[u][t]){
            ++cnt;
            memset(trie[cnt],0,sizeof(trie[cnt]));
            key[cnt]=0;
            trie[u][t]=cnt;
        }
        u=trie[u][t];
        if(i==len-1) key[u]=1;
    }
}

bool query(int k,int l,int r){
    int u=0;
    for(int i=l;i<=r;++i){
        int t=str[k][i]-'a';
        if(!trie[u][t]) return false;
        u=trie[u][t];
    }
    if(!key[u]) return false;
    else return true;
}

int main(){
    memset(trie[0],0,sizeof(trie[0]));
    while(~scanf("%s",str[++n])){
        insert(str[n]);
    }
    --n;
    for(int i=1;i<=n;++i){
        int flag=0,len=strlen(str[i]);
        for(int j=1;j<=len-1;++j)
            if(query(i,0,j-1)&&query(i,j,len-1)){
                flag=1;
                break;
            }
        if(flag) printf("%s
",str[i]);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/FrankChen831X/p/11830405.html