【題解】AtCoder ABC 185E – Sequence Matching

【題目敘述】https://atcoder.jp/contests/abc185/tasks/abc185_e

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

int n, m, a[1005], b[1005], dp[1005][1005];

int main(){
    cin >> n >> m;
    for (int i = 1; i <= n; i++){
        cin >> a[i];
        dp[i][0] = i;
    }
    for (int i = 1; i <= m; i++){
        cin >> b[i];
        dp[0][i] = i;
    }
    for (int i = 1; i <= n; i++){
        for (int j = 1; j <= m; j++){
            if (a[i] == b[j]) dp[i][j] = dp[i-1][j-1];
            else dp[i][j] = min({dp[i-1][j-1]+1, dp[i-1][j]+1, dp[i][j-1]+1});
        }
    }
    cout << dp[n][m] << "\n";
}

分享本文 Share with friends