#include "bits/stdc++.h"
using namespace std;
int main() {
int n, m;
cin >> n >> m;
if (m > n) {
cout << "-1\n";
return 0;
}
string s, t;
cin >> s >> t;
int alp = 26;
vector<vector<int>> sm(alp);
for (int i = 0; i < n; i ++) {
sm[s[i] - 'a'].push_back(i);
}
int maxr = 1e9;
int mn = maxr;
auto dijk = [&](int x){
priority_queue<tuple<int,int,int>> q;
map<pair<int,int>,int> vi;
q.emplace(0, 0, x);
vi[{0, x}] = 0;
while (!q.empty()) {
auto [ds, at, ix] = q.top();
q.pop();
if (ds != vi[{at, ix}]) {
continue;
}
if (at == m - 1) {
mn = min(mn, -ds);
} else {
for (int i : sm[t[at] - 'a']) {
if (!vi.count({at, i}) || ds - abs(i - x) > vi[{at, i}]) {
q.emplace(ds - abs(i - x), at, i);
vi[{at, i}] = ds - abs(i - x);
}
}
for (int i : {-1, 1}) {
if (0 <= ix + i && ix + i < n && t[at + 1] == s[ix + i]) {
if (!vi.count({at + 1, ix + i}) || ds - 1 > vi[{at + 1, ix + i}]) {
q.emplace(ds - 1, at + 1, ix + i);
vi[{at + 1, ix + i}] = ds - 1;
}
}
}
}
}
};
for (int i : sm[t[0] - 'a']) {
dijk(i);
}
if (mn != maxr) {
cout << mn << '\n';
} else {
cout << "-1\n";
}
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
336 KB |
Output is correct |
2 |
Correct |
1 ms |
336 KB |
Output is correct |
3 |
Correct |
1 ms |
336 KB |
Output is correct |
4 |
Incorrect |
1 ms |
336 KB |
Output isn't correct |
5 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
343 ms |
592 KB |
Output is correct |
2 |
Incorrect |
781 ms |
1036 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |