站点图标 陌路寒暄

2.3.1 Longest Prefix 最长前缀

2.3.1 Longest Prefix 最长前缀

时间: 1ms        内存:64M

描述:

在生物学中,一些生物的结构是用包含其要素的大写字母序列来表示的。生物学家对于把长的序列分解成较短的(称之为元素的)序列很感兴趣。 如果一个集合 P 中的元素可以通过串联(允许重复;串联,相当于 Pascal 中的 “+” 运算符)组成一个序列 S ,那么我们认为序列 S 可以分解为 P 中的元素。并不是所有的元素都必须出现。举个例子,序列 ABABACABAAB 可以分解为下面集合中的元素: {A, AB, BA, CA, BBC} 序列 S 的前面 K 个字符称作 S 中长度为 K 的前缀。设计一个程序,输入一个元素集合以及一个大写字母序列,计算这个序列最长的前缀的长度。

输入:

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

输出:

只有一行,输出一个整数,表示 S 能够分解成 P 中元素的最长前缀的长度。

示例输入:

A AB BA CA BBC
.
ABABACABAABC

示例输出:

11

提示:

参考答案(内存最优[1656]):

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

参考答案(时间最优[100]):

/*
ID: zhuihun1
PROG: prefix
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <math.h>
#include <stack>
#define MAXSIZE 205
using namespace std;
ofstream fout ("prefix.out");
ifstream fin ("prefix.in");
string pre[205],str="";
int visited[200001]={0},n=0,l;;
int solve()
{
    const char *start=str.c_str();
    int maxprefix=-1;
    stack<int> stk;
    stk.push(0);visited[0]=1;
    while(!stk.empty())
    {
        int from=stk.top();stk.pop();
        maxprefix = max(maxprefix,from);
		for (int i = 0; i < n; i++)
        {
            l=(int)pre[i].length();
			if (!strncmp(start+from,pre[i].c_str(),l)&&!(visited[from+l]++))
				stk.push(from + l);
        }
    }

    return maxprefix;
}
int main()
{
    string tmp;
    while(cin>>pre[n]&&pre[n]!=".")
        n++;
    while(cin>>tmp)
        str+=tmp;
    cout<<solve();
    return 0;
}

题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。

退出移动版