USACO 2.3.1 Longest Prefix 最长前缀

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;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值