This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define int long long
#define F first
#define S second
#define T int tc; cin >> tc; while(tc--)
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
using namespace std;
const int inf = 1e18;
const int N = 1e6 + 5;
const int M = 505;
const int LOG = 32;
const int CHAR = 26;
const int mod = 1e9 + 7;
const int mod2 = 998244353;
const float pi = atan(1) * 4;
const int dx[] = {1, 0, 0, -1};
const int dy[] = {0, -1, 1, 0};
const char d[] = {'E', 'N', 'S', 'W'};
int n, m, dp[M][M];
string s, ss;
vector<int> pos[CHAR];
int Rec(int i, int j) {
if (j == m) return 0;
int &ret = dp[i][j];
if (ret != -1) return ret;
ret = inf;
if (i - 1 >= 1 && s[i - 1] == ss[j + 1]) ret = min(ret, Rec(i - 1, j + 1) + 1);
if (i + 1 <= m && s[i + 1] == ss[j + 1]) ret = min(ret, Rec(i + 1, j + 1) + 1);
for(auto x: pos[s[i] - 'a']) {
if (x - 1 >= 1 && s[x - 1] == ss[j + 1]) ret = min(ret, Rec(x - 1, j + 1) + abs(i - x) + 1);
if (x + 1 <= m && s[x + 1] == ss[j + 1]) ret = min(ret, Rec(x + 1, j + 1) + abs(i - x) + 1);
}
return ret;
}
main() {
IOS
cin >> n >> m >> s >> ss;
s = '.' + s;
ss = '.' + ss;
for(int i = 1; i < s.size(); i++) pos[s[i] - 'a'].push_back(i);
memset(dp, -1, sizeof dp);
int ans = inf;
for(int i = 1; i <= n; i++) {
if (s[i] == ss[1])
ans = min(ans, Rec(i, 1));
}
if (ans >= inf) ans = -1;
cout << ans;
}
Compilation message (stderr)
bajka.cpp:37:1: warning: ISO C++ forbids declaration of 'main' with no type [-Wreturn-type]
37 | main() {
| ^~~~
bajka.cpp: In function 'int main()':
bajka.cpp:42:22: warning: comparison of integer expressions of different signedness: 'long long int' and 'std::__cxx11::basic_string<char>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
42 | for(int i = 1; i < s.size(); i++) pos[s[i] - 'a'].push_back(i);
| ~~^~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |