洛谷 P1470 [USACO2.3] 最长前缀 Longest Prefix
题意
给定一个字符串集合P和字符串S , 找出S由P中字符串组成的最长前缀 , P中元素可以重复使用
思路
设\(f(i)\)为\(1-i\)位置都可以 , 考虑接下来的从\(i+1\)开始的字符串 , 枚举每一个集合中的字符串 , 如果\(i+1\)开始的和之前的相同 , 那么更新\(f\)
代码
#include<bits/stdc++.h>
using namespace std;
string s;
const int N = 1e6+10;
vector<string>v;
bool f[N];
int main() {
int idx = 0;
while (cin>>s) {
if (s==".") {
break;
}
v.push_back(s);
idx++;
}
s="";
string tmp;
while (cin>>tmp) {
s += tmp;
}
s = " "+ s;
int maxn=0;
f[0] = true;
for (int i = 1; i< s.size(); i++) {
for (auto e : v) {
if (f[i-e.size()]) {
if (e == s.substr(i-e.size() + 1,e.size())) {
f[i] = true;
maxn = max(maxn,i);
}
}
}
}
cout<<maxn<<"\n";
return 0;
}