USACO Section 2.3 Longest Prefix

题意:

给你一大堆小字符串  和  一个大字符串  求  使用小字符串能拼出的大字符串的前缀最长是多少


思路:

由于数据不大  所以可以尝试扫描大字符串  每到一个位置用小字符串拼一下看看能拼多长  拼的最远距离就是答案

我用trie树来存小字符串集合  扫描大字符串时  如果该位置是可以向后延伸的(即之前能拼到这个位置)

那么我用一个标记在trie树上爬  每次发现一个小字符串结束标志  就表示对应大字符串的位置是可延伸的

这样做下标记并更新答案


注意:

这题的坑是这句话 —— “the input file contains a sequence S (length 1..200,000) expressed as one or more lines, none of which exceeds 76 letters in length”  他的大字符串是分几行输入的… 千万不要只用一个%s去读入


代码:

/*
ID: housera1
PROG: prefix
LANG: C++
*/
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

struct node
{
	int flag;
	int next[28];
}trie[20100];
char tmp[210],str[200010]={0};
int vis[200010];
int n=1,ans=0;

void make_tree()
{
	int i=0,len=strlen(tmp),now=0;
	for(;i<len;i++)
	{
		if(trie[now].next[tmp[i]-'A']!=-1) now=trie[now].next[tmp[i]-'A'];
		else
		{
			trie[now].next[tmp[i]-'A']=n;
			trie[n].flag=0;
			for(int j=0;j<26;j++) trie[n].next[j]=-1;
			now=n;
			n++;
		}
	}
	trie[now].flag=1;
}

void run(int start,int L)
{
	int i,j;
	for(i=start,j=0;;i++)
	{
		if(trie[j].flag)
		{
			vis[i]=1;
			ans=max(ans,i);
		}
		if(trie[j].next[str[i]-'A']!=-1) j=trie[j].next[str[i]-'A'];
		else break;
	}
}

int main(){
	int Debug=0;
	if(!Debug){
		freopen("prefix.in","r",stdin);
		freopen("prefix.out","w",stdout);
	}
	int i,len;
	trie[0].flag=0;
	for(i=0;i<26;i++) trie[0].next[i]=-1;
	while(scanf("%s",tmp))
	{
		if(strcmp(tmp,".")==0) break;
		make_tree();
	}
	while(~scanf("%s",tmp))
	{
		strcat(str,tmp);
	}
	len=strlen(str);
	for(i=0,vis[0]=1;i<len;i++)
	{
		if(vis[i]) run(i,len);
	}
	printf("%d\n",ans);
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值