1. 程式人生 > 實用技巧 >[CF1446B] Catching Cheaters - dp

[CF1446B] Catching Cheaters - dp

Description

給定兩個串 \(s,t\),長度 \(\le 5000\),求對所有 \(s\) 的子串 \(p\)\(t\) 的子串 \(q\)\(4LCS(p,q)-|p|-|q|\) 的最大值。LCS 指最長公共子序列。

Solution

\(f[i][j]\) 表示 \(s\) 考慮到第 \(i\) 個字元,\(t\) 考慮到第 \(j\) 個字元,兩個字首中所存在的 LCS 的最大長度。

轉移時主要結合一下 LCS 與最大子段和的思想,即 if(s[i]==t[j]) f[i][j]=max(f[i-1][j-1],0ll)+2;else f[i][j]=max(f[i][j-1],f[i-1][j])-1;

#include <bits/stdc++.h>
using namespace std;

#define int long long 
const int N = 5005;

int f[N][N];
char s[N],t[N];
int n,m;

signed main()
{
    ios::sync_with_stdio(false);

    cin>>n>>m>>s+1>>t+1;
    
    int ans=0;

    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(s[i]==t[j]) f[i][j]=max(f[i-1][j-1],0ll)+2;
            else f[i][j]=max(f[i][j-1],f[i-1][j])-1;
            ans=max(ans,f[i][j]);
        }
    }

    cout<<ans<<endl;
}