现在的位置: 首页 > 综合 > 正文

BZOJ 1212 HNOI 2004 L语言 Trie树

2018年01月19日 ⁄ 综合 ⁄ 共 1025字 ⁄ 字号 评论关闭

题目大意:给出一些单词,和一些句子,当且仅当句子可以分割成的子串都可以被词典翻译,就说明这个子串是可以被翻译的。求最长的可以被翻译的前缀长度。

思路:利用Trie树来刷数组,能够刷到的最长的地方就是这个串最长可以翻译到的地方。

PS:在BZOJ上Trie居然比AC自动机快,我的渣代码都刷到第一篇了。。。

CODE:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
 
struct Trie{
    Trie *son[27];
    bool end;
     
    Trie() {
        memset(son,NULL,sizeof(son));
        end = false;
    }
}*root = new Trie();
 
int words,cnt;
char s[1 << 20|100],temp[20];
bool f[1 << 20|100];
 
inline void Insert(char *s)
{
    Trie *now = root;
    while(*s != '\0') {
        if(now->son[*s - 'a'] == NULL)
            now->son[*s - 'a'] = new Trie();
        now = now->son[*s - 'a'];
        ++s;
    }
    now->end = true;
}
 
inline void Ask(char *s,int i)
{
    Trie *now = root;
    int t = 0;
    while(*s != '\0') {
        if(now->son[*s - 'a'] == NULL)
            return ;
        now = now->son[*s - 'a'];
        ++s;
        ++t;
        if(now->end) f[i + t] = true;
    }
    if(now->end) f[i + t] = true;
}
 
inline int Work()
{
    memset(f,false,sizeof(f));
    f[0] = true;
    int re = 0,length = strlen(s + 1);
    for(int i = 0; i <= length; ++i) {
        if(!f[i])   continue;
        re = i;
        Ask(s + i + 1,i);
    }
    return re;
}
 
int main()
{
    cin >> words >> cnt;
    for(int i = 1; i <= words; ++i) {
        scanf("%s",temp);
        Insert(temp);
    }
    for(int i = 1; i <= cnt; ++i) {
        scanf("%s",s + 1);
        printf("%d\n",Work());
    }
    return 0;
}

抱歉!评论已关闭.