USACO Longest Prefix

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
ID: wcr19961
PROG: prefix
LANG: C++11
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;

typedef long long LL;
const int maxn = 200010;
const int maxm = 210;
string s;
string e[maxm];
char tmp[maxn];
bool dp[maxn];

int main() {
freopen("prefix.in", "r", stdin);
freopen("prefix.out", "w", stdout);
int n = 0, ans = 0;
while (~scanf("%s", tmp) && tmp[0] != '.') {
e[n++] = tmp;
}
sort(e, e + n);
while (~scanf("%s", tmp)) {
s += tmp;
}
dp[0] = true;
for (int i = 0; i < s.length(); ++i) {
if (dp[i]) {
for (int j = 1; j <= 10 && i + j <= s.length(); ++j) {
if (!dp[i + j] && binary_search(e, e + n, s.substr(i, j))) {
dp[i + j] = true;
ans = max(ans, i + j);
}
}
}
}
printf("%d\n", ans);
return 0;
}