![](http://cerberus.delos.com:791/usaco/cow1.jpg)
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;
}