1. 程式人生 > 實用技巧 >2020 Multi-University Training Contest 2 String Distance

2020 Multi-University Training Contest 2 String Distance

2020 Multi-University Training Contest 2 String Distance

題解:

這個官方題解說的很清楚了,比賽的時候沒有時間想了,讓我想可能也想不到,挺思維的。

#include <bits/stdc++.h>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int maxn = 2e5+10;
int g[maxn][30],f[30][30];
char a[maxn],b[maxn];
int main() {
    int t;
    scanf("%d", &t);
    while (t--) {
        scanf("%s%s", a + 1, b + 1);
        int n = strlen(a + 1), m = strlen(b + 1);
        for (int i = 1; i <= n+10; i++) memset(g[i], inf, sizeof(g[i]));
        for (int i = n; i >= 1; i--) {
            int x = a[i] - 'a' + 1;
            g[i][x] = i;
            for (int j = 1; j <= 26; j++) g[i][j] = min(g[i][j], g[i + 1][j]);
        }
        int q;
        scanf("%d", &q);
        while (q--) {
            int l, r;
            scanf("%d%d", &l, &r);
            memset(f, inf, sizeof(f));
            f[0][0] = l - 1;
            for (int i = 1; i <= m; i++) {
                int x = b[i] - 'a' + 1;
//                printf("i=%d\n",i);
                for (int j = 0; j <= min(i,r-l+1); j++) {
                    if (j == 0) f[i][j] = l - 1;
                    f[i][j] = min(f[i - 1][j], f[i][j]);
                    if(j>=1&&f[i - 1][j - 1]!=inf) f[i][j]=min(f[i][j],g[f[i - 1][j - 1]+1][x]);

//                    printf("f[%d][%d]=%d\n",i,j,f[i][j]);
                }
            }
            ll ans = r - l + 1 + m;
//            printf("ans=%lld\n",ans);
            for(int j=m;j>=0;j--){
                if(f[m][j]<=r){
//                    printf("j=%d\n",j);
                    ans -= 2*j;
                    break;
                }
            }
            printf("%lld\n",ans);
        }
    }
    return 0;
}

/*
1
qaqaqwqaqaq
qaqwqaq
3
3 9
1 7
2 8
 */