이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
map<char, vector<int>> mp; // positions where a letter shows up
const int INF = 1e9 + 5;
int n, m, ans = INF;
string scary, fav;
void go(int at, int id, int cost, bool used2) {
if (id == m-1) {
ans = min(ans, cost);
//cout << at << " " << id << " " << cost << " " << used2 << "\n";
return;
}
// use move1
// go left
if (at > 0 && scary[at-1] == fav[id+1]) {
go(at - 1, id+1, cost + 1, 0);
}
// go right
if (at < n-1 && scary[at+1] == fav[id+1]) {
go(at + 1, id+1, cost + 1, 0);
}
// use move2
if (used2) return;
for(int i : mp[scary[at]]) {
go(i, id, cost + abs(at - i), 1);
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> m >> scary >> fav;
for(int i = 0; i < n; i++) {
mp[scary[i]].push_back(i);
}
for(int i : mp[fav[0]]) {
go(i, 0, 0, 1);
}
cout << (ans >= INF ? -1 : ans) << "\n";
return 0;
}
//~ check for overflows
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |