一 原题
IOI'96
The structure of some biological objects is represented by the sequence of their constituents, where each part is denoted by an uppercase letter. Biologists are interested in decomposing a long sequence into shorter sequences called primitives.
We say that a sequence S can be composed from a given set of primitives P if there is a some sequence of (possibly repeated) primitives from the set whose concatenation equals S. Not necessarily all primitives need be present. For instance the sequence ABABACABAABcan be composed from the set of primitives
{A, AB, BA, CA, BBC}
The first K characters of S are the prefix of S with length K. Write a program which accepts as input a set of primitives and a sequence of constituents and then computes the length of the longest prefix 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 of upper-case characters on one or more lines. The list of primitives is terminated 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 letters in length. The "newlines" (line terminators) are not part of the string 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 longest prefix that can be composed from the set P.SAMPLE OUTPUT (file prefix.out)
11
二 分析
三 代码
USER: Qi Shen [maxkibb3] TASK: prefix LANG: C++ Compiling... Compile: OK Executing... Test 1: TEST OK [0.000 secs, 4572 KB] Test 2: TEST OK [0.000 secs, 4572 KB] Test 3: TEST OK [0.000 secs, 4572 KB] Test 4: TEST OK [0.000 secs, 4572 KB] Test 5: TEST OK [0.000 secs, 4572 KB] Test 6: TEST OK [0.130 secs, 4572 KB] All tests OK.
Your program ('prefix') produced all correct answers! This is your submission #2 for this problem. Congratulations!
AC代码:/*
ID:maxkibb3
LANG:C++
PROG:prefix
*/
#include<cstdio>
#include<cstring>
using namespace std;
int n, m;
char pri[205][15];
int len[205];
char target[200005];
bool dp[200005];
bool cmp(char *a, char *b, int len) {
for(int i = 0; i < len; i++) {
if(*a != *b) return false;
a++; b++;
}
return true;
}
int main() {
freopen("prefix.in", "r", stdin);
freopen("prefix.out", "w", stdout);
while(true) {
scanf("%s", pri[n]);
len[n] = strlen(pri[n]);
n++;
char s = getchar();
if(pri[n - 1][0] == '.') {
n--;
break;
}
}
while(true) {
if(scanf("%s", target + m) == -1) break;
m = strlen(target);
}
//printf("%d\n", m);
dp[0] = true;
for(int i = 1; i <= m; i++) {
if(dp[i]) continue;
for(int j = 0; j < n; j++) {
if(i < len[j]) continue;
if(!cmp(target + i - len[j], pri[j], len[j])) continue;
if(dp[i - len[j]]) dp[i] = true;
}
}
for(int i = m; i >= 0; i--) {
if(dp[i]) {
printf("%d\n", i);
break;
}
}
return 0;
}