CF1303E - Erase Subsequences DP

CF1303E - Erase Subsequences

题意

两个字符串 s s s t t t,问是否存在 s s s的两个没有交集的子串拼接成 t t t串,即 t = t 1 + t 2 t=t1+t2 t=t1+t2 t 1 , t 2 t1,t2 t1,t2可以是空串
1 ≤ ∣ t ∣ ≤ ∣ s ∣ ≤ 400 1\leq |t| \leq |s|\leq400 1ts400

题解

看字符串长度,应该是 O ( N 3 ) O(N^3) O(N3)
最直接的想法就是把 t t t串分成两部分 t 1 , t 2 t1,t2 t1,t2,然后匹配 s s s串,保证 t 1 , t 2 t1,t2 t1,t2不用同一个字符就行
f [ i ] [ j ] f[i][j] f[i][j]为匹配到 s [ i ] s[i] s[i] t 1 [ j ] t1[j] t1[j] t 2 t2 t2的最大的匹配位置,只要最后 f [ ∣ s ∣ ] [ ∣ t 1 ∣ ] = ∣ t 2 ∣ f[|s|][|t1|]=|t2| f[s][t1]=t2就说明能够找到
状态转移方程:

s [ i ] s[i] s[i]匹配 t 1 t1 t1
t 1 t1 t1已经匹配到 j j j,下一位是 j + 1 j+1 j+1
f [ i ] [ j + 1 ] = m a x ( f [ i ] [ j + 1 ] , f [ i − 1 ] [ j ] ) f[i][j+1]=max(f[i][j+1],f[i-1][j]) f[i][j+1]=max(f[i][j+1],f[i1][j])

s [ i ] s[i] s[i]匹配 t 2 t2 t2
t 2 t2 t2已经匹配到 f [ i − 1 ] [ j ] f[i-1][j] f[i1][j],下一位是 f [ i − 1 ] [ j ] + 1 f[i-1][j]+1 f[i1][j]+1
f [ i ] [ j ] = m a x ( f [ i ] [ j ] , f [ i − 1 ] [ j ] + ( s [ i ] = = t [ ∣ t 1 ∣ + f [ i − 1 ] [ j ] + 1 ] ) f[i][j]=max(f[i][j],f[i-1][j]+(s[i]==t[|t1|+f[i-1][j]+1]) f[i][j]=max(f[i][j],f[i1][j]+(s[i]==t[t1+f[i1][j]+1])
相等匹配长度加一,不相等不变

代码

#include 
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int MAX = 4e2 + 10;

int T, N, M;
char s[MAX], t[MAX];
int f[MAX][MAX];//f[i][j]表示s串匹配到i, t1匹配到j时, t2最大的匹配位置

void init() {
    for (int i = 0; i <= N; i++)
        for (int j = 0; j <= M; j++)
            f[i][j] = j == 0 ? 0 : -INF;
}

int main() {
    scanf("%d", &T);
    while (T--) {
        scanf("%s%s", s + 1, t + 1);
        N = strlen(s + 1), M = strlen(t + 1);
        int flag = 0;
        for (int pre = 0; pre < M; pre++) {//t1长度
            int suf = M - pre;//t2长度
            init();
            for (int i = 1; i <= N; i++) {
                for (int j = 0; j <= pre; j++)
                    if (f[i - 1][j] != -INF) {
                        //与t1匹配
                        if (j < pre && s[i] == t[j + 1]) f[i][j + 1] = max(f[i][j + 1], f[i - 1][j]);
                        //与t2匹配, 匹配上长度+1
                        f[i][j] = max(f[i][j], f[i - 1][j] + (pre + f[i - 1][j] + 1 <= M && s[i] == t[pre + f[i - 1][j] + 1]));
                    }
            }
            if (f[N][pre] == suf) {
                flag = 1;
                break;
            }
        }
        printf("%s\n", flag ? "YES" : "NO");
    }

    return 0;
}

你可能感兴趣的:(Codeforces,DP)