mirror of
https://gitcode.com/Zengtudor/alg2025.git
synced 2025-12-16 12:13:03 +00:00
refactor(P3102): 重构字符串处理逻辑为动态规划实现
将原有的暴力匹配算法重构为基于动态规划的解决方案,提高计算效率 添加了调试输出和模数运算支持
This commit is contained in:
parent
66740ddb77
commit
3c29bca56e
@ -1,34 +1,57 @@
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <iostream>
|
||||
#include <istream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
using ll = int64_t;
|
||||
|
||||
#define printf
|
||||
const ll p=2014;
|
||||
std::string s;
|
||||
ll ans;
|
||||
ll n;
|
||||
std::vector<std::vector<ll>> dp;
|
||||
|
||||
int main(){
|
||||
std::cin.tie(nullptr);
|
||||
std::iostream::sync_with_stdio(false);
|
||||
|
||||
std::cin>>s;
|
||||
for(ll i=1;i<s.size();i++){
|
||||
ll l1=i,l2=s.size()-i;
|
||||
for(ll j=0;j<std::min(l1,l2);j++){
|
||||
if(s[j]!=s[i+j]){
|
||||
goto nxt1;
|
||||
}
|
||||
static inline ll dfs(const ll l,const ll r){
|
||||
struct S{
|
||||
const ll &l,&r,&dp;
|
||||
S(const ll&l,const ll&r,const ll&dp):l(l),r(r),dp(dp){
|
||||
printf("dfs l=%lld, r=%lld, START\n",l,r);
|
||||
}
|
||||
ans++;
|
||||
~S(){
|
||||
printf("dfs l=%lld, r=%lld, ret=%lld\n",l,r,dp);
|
||||
}
|
||||
}raii(l,r,dp[l][r]);
|
||||
const ll nlen=r-l+1;
|
||||
if(l>r)return 0;
|
||||
if(dp[l][r])return dp[l][r];
|
||||
dp[l][r]=1;
|
||||
if(nlen<=2)return dp[l][r]=1;
|
||||
for(ll i=l+1;i<=r;i++){
|
||||
if(i-l==r-i+1)continue;
|
||||
const ll clen=std::min(i-l,r-i+1);
|
||||
if(i-l==1&&r-i+1==1)continue;
|
||||
for(ll j=0;j<clen;j++){
|
||||
if(s[l+j]!=s[i+j])goto nxt1;
|
||||
}
|
||||
dp[l][r]=((i-l>r-i+1?dfs(l, i-1):dfs(i, r))+dp[l][r])%p;
|
||||
nxt1:;
|
||||
for(ll j=0;j<std::min(l1,l2);j++){
|
||||
if(s[i-1-j]!=s[s.size()-1-j]){
|
||||
goto nxt2;
|
||||
}
|
||||
for(ll j=0;j<clen;j++){
|
||||
if(s[i-1-j]!=s[r-j])goto nxt2;
|
||||
}
|
||||
ans++;
|
||||
dp[l][r]=((i-l>r-i+1?dfs(l, i-1):dfs(i, r))+dp[l][r])%p;
|
||||
nxt2:;
|
||||
}
|
||||
std::cout<<ans*2<<"\n";
|
||||
return dp[l][r];
|
||||
}
|
||||
|
||||
int main(){
|
||||
std::iostream::sync_with_stdio(false);
|
||||
std::cin.tie(nullptr);
|
||||
|
||||
std::cin>>s;
|
||||
n=s.size();
|
||||
s=' '+s;
|
||||
dp.resize(n+1,std::vector<ll>(n+1));
|
||||
std::cout<<(dfs(1,n)-1+p)%p<<"\n";
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user