您的位置:首页 > 其它

最长前缀 [Codevs 2778][USACO]

2016-06-24 09:47 405 查看

题目描述 Description

在生物学中,一些生物的结构是用包含其要素的大写字母序列来表示的。生物学家对于把长的序列分解成较短的序列(即元素)很感兴趣。

如果一个集合 P 中的元素可以通过串联(元素可以重复使用,相当于 Pascal 中的 “+” 运算符)组成一个序列 S ,那么我们认为序列 S 可以分解为 P 中的元素。元素不一定要全部出现(如下例 BBC 就没有出现)。举个例子,序列 ABABACABAAB 可以分解为下面集合中的元素:{A,AB,BA,CA,BBC}

序列 S 的前面 K 个字符称作 S 中长度为 K 的前缀。设计一个程序,输入一个元素集合以及一个大写字母序列 S ,设 S′ 是序列S的最长前缀,使其可以分解为给出的集合 P 中的元素,求 S′ 的长度 K 。

输入描述 Input Description

输入数据的开头包括 1...200 个元素(长度为 1...10 )组成的集合,用连续的以空格分开的字符串表示。字母全部是大写,数据可能不止一行。元素集合结束的标志是一个只包含一个 “.” 的行。集合中的元素没有重复。接着是大写字母序列 S ,长度为 1...200,000 ,用一行或者多行的字符串来表示,每行不超过 76 个字符。换行符并不是序列 S 的一部分。

输出描述 Output Description

只有一行,输出一个整数,表示 S 符合条件的前缀的最大长度。

样例输入 Sample Input

A AB BA CA BBC

.

ABABACABAABC

样例输出 Sample Output

11

分析 I Think

我们可以建一颗字母树来储存集合 P 中的元素,这样在每一查找时就可以直接在树中寻找是否存在对应的单词。

代码 Code

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

typedef struct node{

node *child[26];
bool leaf[26];

node(){memset(leaf,false,sizeof leaf);memset(child,NULL,sizeof child);}

}*pnode;

pnode trie = new node;
char word[200100];
int length;
char base[200];
bool pre[200100];

void read();
void insert(pnode &,const char *);
void query(pnode ,const char *,bool *);

int main(){

read();

pre[0] = true;
for(int i=1;i<=length;++i){
while(!pre[i-1] && i<=length)
++i;
query(trie,word+i,pre+i);
}

for(int i=length;i>=0;--i)
if(pre[i]){
printf("%d\n",i);
break;
}

return 0;

}

void read(){

char ch = getchar();
int i = 0;

while(true){
i = 0;
while(ch!='.' && (ch>'Z'||ch<'A'))
ch = getchar();
if(ch == '.')
break;
while(ch>='A' && ch<='Z'){
base[i++] = ch;
ch = getchar();
}
base[i] = 0;
insert(trie,base);
}

while(true){
while(ch!=EOF && (ch>'Z'||ch<'A'))
ch = getchar();
if(ch == EOF)
break;
while(ch>='A' && ch<='Z'){
word[++length] = ch;
ch = getchar();
}
}

}

void insert(pnode &root,const char *str){

if(!root->child[*str-'A'])
root->child[*str-'A'] = new node;

if(!*(str+1))
root->leaf[*str-'A'] = true;
else
insert(root->child[*str-'A'],str+1);

}

void query(pnode root,const char *str,bool *p){

if(!*str || !root->child[*str-'A'])
return ;

if(root->leaf[*str-'A'])
*p = true;

query(root->child[*str-'A'],str+1,p+1);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: