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 <iostream>
#include <vector>
#include <algorithm>
#include <set>
#include <queue>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
int n, m;
string s, t;
cin >> n >> m >> s >> t;
vector<set<pair<int, int>>> graph(n);
for (int i = 0; i < n; i++) {
if (i > 0) {
graph[i].insert({i-1, 1});
graph[i-1].insert({i, 1});
} else if (i < n-1) {
graph[i].insert({i+1, 1});
graph[i+1].insert({i, 1});
}
for (int j = 0; j < n; j++) {
if (s[i] == s[j]) { // add s[j] adjacents
if (j > 0 && i != j-1) {
graph[i].insert({j-1, abs(i - (j-1))});
graph[j-1].insert({i, abs(i - (j-1))});
} else if (j < n-1 && i != j+1) {
graph[i].insert({j+1, abs(i - (j+1))});
graph[j+1].insert({i, abs(i - (j+1))});
}
}
}
}
priority_queue<pair<int, pair<int, int>>> pq; // cost, s_i, t_j
vector<vector<int>> dp(n, vector<int>(m, 1e9));
for (int i = 0; i < n; i++) {
if (s[i] == t[0]) {
pq.push({0, {i, 0}});
dp[i][0] = 0;
}
}
while (!pq.empty()) {
int cost = pq.top().first;
int i = pq.top().second.first;
int j = pq.top().second.second;
pq.pop();
dp[i][j] = min(dp[i][j], cost);
if (j == m-1) {
continue;
}
for (pair<int, int> p: graph[i]) {
int k = p.first;
int c = p.second;
if (s[k] == t[j+1] && cost + c <= dp[k][j+1]) {
pq.push({cost + c, {k, j+1}});
}
}
}
int ans = 1e9;
for (int i = 0; i < n; i++) {
ans = min(ans, dp[i][m-1]);
}
if (ans == 1e9) ans = -1;
cout << ans << '\n';
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |