#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ar array
const int INF = 1e9;
int n, m;
string s, t;
vector<int> pos[26];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m >> s >> t;
for (int i = 0; i < n; ++i) pos[s[i] - 'a'].push_back(i);
if (pos[t[0] - 'a'].empty()) {
cout << -1;
return 0;
}
vector<int> dp(pos[t[0] - 'a'].size());
for (int i = 1; i < m; ++i) {
int c = t[i] - 'a';
int c2 = t[i - 1] - 'a';
vector<int> ndp(pos[c].size(), INF);
for (int j = 0; j < pos[c2].size(); ++j) {
for (int k = 0; k < pos[c].size(); ++k) {
if (abs(pos[c2][j] - pos[c][k]) == 1) {
ndp[k] = min(ndp[k], dp[j] + 1);
}
}
}
swap(dp, ndp);
for (int i = 0; i < dp.size(); ++i) {
for (int j = 0; j < dp.size(); ++j) {
dp[j] = min(dp[j], dp[i] + abs(pos[c][i] - pos[c][j]));
}
}
if (dp.empty() || *min_element(dp.begin(), dp.end()) == INF) {
cout << -1;
return 0;
}
}
cout << *min_element(dp.begin(), dp.end());
return 0;
}
Compilation message
bajka.cpp: In function 'int main()':
bajka.cpp:26:21: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
26 | for (int j = 0; j < pos[c2].size(); ++j) {
| ~~^~~~~~~~~~~~~~~~
bajka.cpp:27:22: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
27 | for (int k = 0; k < pos[c].size(); ++k) {
| ~~^~~~~~~~~~~~~~~
bajka.cpp:34:21: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
34 | for (int i = 0; i < dp.size(); ++i) {
| ~~^~~~~~~~~~~
bajka.cpp:35:22: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
35 | for (int j = 0; j < dp.size(); ++j) {
| ~~^~~~~~~~~~~
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
364 KB |
Output is correct |
2 |
Correct |
1 ms |
364 KB |
Output is correct |
3 |
Correct |
1 ms |
364 KB |
Output is correct |
4 |
Correct |
1 ms |
364 KB |
Output is correct |
5 |
Correct |
0 ms |
364 KB |
Output is correct |
6 |
Correct |
1 ms |
364 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
364 KB |
Output is correct |
2 |
Correct |
3 ms |
364 KB |
Output is correct |
3 |
Correct |
1 ms |
364 KB |
Output is correct |
4 |
Correct |
1 ms |
364 KB |
Output is correct |
5 |
Correct |
1 ms |
364 KB |
Output is correct |
6 |
Correct |
1 ms |
364 KB |
Output is correct |
7 |
Correct |
6 ms |
364 KB |
Output is correct |
8 |
Correct |
23 ms |
364 KB |
Output is correct |
9 |
Correct |
38 ms |
364 KB |
Output is correct |
10 |
Correct |
1 ms |
364 KB |
Output is correct |
11 |
Correct |
4 ms |
364 KB |
Output is correct |