一维的dp,设dp[i]表示主串S中从i开始的最长的可组成的前缀,dp[1]就是所求,状态转移方程:
{dp[i]=max{dp[j]+j-i} 其中:i 到 j-1 的字串是属于集合P 且 j 要满足 i<j && j< n && j<=i+10(最后这个限制很重要)
USER: li xiaopeng [xpli1] TASK: prefix LANG: C++ Compiling... Compile: OK Executing... Test 1: TEST OK [0.000 secs, 3708 KB] Test 2: TEST OK [0.011 secs, 3708 KB] Test 3: TEST OK [0.000 secs, 3708 KB] Test 4: TEST OK [0.022 secs, 3708 KB] Test 5: TEST OK [0.065 secs, 3708 KB] Test 6: TEST OK [0.464 secs, 3724 KB] All tests OK.Your program ('prefix') produced all correct answers! This is your submission #9 for this problem. Congratulations!
/* ID: xpli1 PROG: prefix LANG: C++ */
#include <iostream> #include <fstream> #include <string>
using namespace std;
#define IN fin #define OUT fout #define max(a,b) (((a) > (b)) ? (a) : (b))
ifstream fin ("prefix.in", ios::in);
ofstream fout("prefix.out",ios::out);
string P[201]; string S; int max_len; int dp[200001];
int main(){
string temp;
int i,j,k,index = 0;
while(IN >> temp, temp != ".") { P[index++] = temp; }
while(IN >> temp) { S += temp; }
int lens = S.length();
for(i = lens - 1; i >= 0; i--){
for(j = i + 1; j <= lens && j <= i + 10; j++){
for(k = 0; k < index; k++){
if(P[k].length() != j-i) continue;
if(S.compare(i,j-i,P[k]) == 0) { dp[i] = max(dp[i],dp[j] + j - i); }
}
}
}
OUT << dp[0] << endl;
return 0; }
本文介绍了一种使用一维动态规划方法来解决字符串前缀匹配问题的技术。通过定义状态dp[i]为字符串S从位置i开始的最长可组成前缀长度,并给出状态转移方程,实现了高效的解决方案。
355

被折叠的 条评论
为什么被折叠?



