您的位置:首页 > 其它

USACO 2.3.1 Longest Prefix 最长前缀

2013-08-04 20:51 330 查看

Longest Prefix

IOI'96

The structure of some biological objects is represented by thesequence of their constituents, where each part is denote by anuppercase letter. Biologists are interested in decomposing a longsequence into shorter ones called
primitives.

We say that a sequence S can be composed from a given set of primitivesP if there is a some sequence of (possibly repeated) primitives fromthe set whose concatenation equals S. Not necessarily all primitivesneed be present. For instance the sequence
ABABACABAABcan becomposed from the set of primitives

{A, AB, BA, CA, BBC}

The first K characters of S are the prefix of S with lengthK. Write a program which accepts as input a set of primitives anda sequence of constituents and then computes the length of the longestprefix that can be composed from primitives.

PROGRAM NAME: prefix

INPUT FORMAT

First, the input file contains the list (length 1..200) of primitives(length 1..10) expressed as a series of space-separated strings ofupper-case characters on one or more lines. The list of primitives isterminated by a line that contains nothing more than
a period (`.').No primitive appears twice in the list.Then, the input file contains a sequence S (length 1..200,000)expressed as one or more lines, none of which exceeds 76 lettersin length. The "newlines" (line terminators) are not part of thestring S.

SAMPLE INPUT (file prefix.in)

A AB BA CA BBC
.
ABABACABAABC

OUTPUT FORMAT

A single line containing an integer that is the length of the longestprefix that can be composed from the set P.

SAMPLE OUTPUT (file prefix.out)

11

题意:给出一个集合,一个字符串,找出这个字符串的最长前缀,使得前缀可以划分为这个集合中的元素(集合中的元素可以不全部使用)。

解题思路:从字符串下表为0的位置开始匹配集合中的元素,匹配时最大长度为当前位置+该元素的长度,然后下表后移一位,继续往后找。。。最后得到的长度就是所求。

源代码:

/*
ID: supersnow0622
PROG: prefix
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string.h>

using namespace std;
char assemble[210][15];
string str;
int main() {
ofstream fout ("prefix.out");
ifstream fin ("prefix.in");
int count=0,Max=0;
while(cin>>assemble[count]&&assemble[count++][0]!='.');
str="";
string s;
while(cin>>s)
str+=s;
for(int i=0;i<str.length();i++)
{
for(int j=0;j<count;j++)
{
if(i+strlen(assemble[j])<=str.length())
{
bool judge=true;
for(int k=0;k<strlen(assemble[j]);k++)
if(str[i+k]!=assemble[j][k])
{
judge=false;break;
}
if(judge)
if(Max<i+strlen(assemble[j]))
Max=i+strlen(assemble[j]);
}
}
if(i+1>Max)
break;
}
cout<<Max;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: