이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <iostream>
#include <vector>
#include <bitset>
#include <queue>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <set>
#include <map>
#include <cassert>
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define ll long long
#define ii pair<int,int>
#define pll pair<long long, long long>
#define fi first
#define se second
#define r first
#define c second
#define all(x) x.begin(), x.end()
ostream& operator << (ostream& os, pair<int, int> a) {
    return os << a.first << " : " << a.second;
}
#define endl '\n'
#define db(val) "["#val" = "<<(val)<<"] "
#define cntbit(x) __builtin_popcount(x)
const int N = 500 + 5;
const int iINF = 1e9;
const ll MOD = 1e9 + 7;
const ll MOD2 = 998244353;
const ll INF = 1e18;
int n, m;
string s, t;
ll dp[N][N];
int main() {
    #ifdef CHUNGDINH
    freopen("main.inp","r",stdin);
    //freopen("main.out","w",stdout);
    #endif
    cin >> n >> m >> s >> t;
    s = '#' + s, t = '#' + t;
    if (m == 1) {
        if (s == t) cout << 0; else cout << -1;
        return 0;
    }
    for (int i = 1; i <= n; i++) {
        dp[i][1] = INF;
        if (s[i] == t[1]) dp[i][1] = 0;
    }
    ll res = INF;
    for (int k = 2; k <= m; k++) {
        for (int i = 1; i <= n; i++) {
            dp[i][k] = INF;
            if (s[i] != t[k]) continue;
            for (int j = 1; j <= n; j++) {
                if (s[j] != t[k - 1]) continue;
                int dis;
                if (i == j) dis = 2;
                else dis = abs(i - j);
                dp[i][k] = min(dp[i][k], dp[j][k - 1] + dis);
            }
            if (k == m) res = min(res, dp[i][k]);
        }
    }
    if (res >= INF) res = -1;
    cout << res;
}
/*
Array bounds *
long long vs int
Garbage value
Sometimes, VNOI views "arrays out of bounds" as "wrong answer"
*/
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... |