L3-020 至多删三个字符 (30 分)
思路:
线性dp
题解
类似这个题
dp好难,我学不明白
code:
#include<bits/stdc++.h>
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define ld long double
#define all(x) x.begin(), x.end()
#define mem(x, d) memset(x, d, sizeof(x))
#define eps 1e-6
using namespace std;
const int maxn = 2e6 + 9;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
ll n, m;
ll f[maxn][4];
void work()
{
string s;cin >> s;n = s.size(); s = "@" + s;
f[0][0] = 1;
for(int i = 1; i <= n; ++i){
for(int j = 0; j <= 3; ++j){
if(j >= 1) f[i][j] += f[i-1][j-1];//删 i
f[i][j] += f[i-1][j];// 不删 i
for(int k = i - 1; k >= 1 && i - k <= j; --k)// 去重
{//
if(s[k] == s[i]){
f[i][j] -= f[k-1][j - (i - k)];
break;
}
}
}
}
/*for(int i = 1; i <= n; ++i)
for(int j = 0; j <= 3; ++j)
cout << f[i][j] << " \n"[j==3];*/
ll ans = 0;
for(int i = 0; i < 4; ++i)
ans += f[n][i];
cout << ans;
}
int main()
{
ios::sync_with_stdio(0);
// int TT;cin>>TT;while(TT--)
work();
return 0;
}