#include<bits/stdc++.h>
using namespace std;
long long n, m, mini = INT_MAX;
string s, str;
long long backtrack(int pos, int x)
{
if(x == m) return 0;
long long temp = INT_MAX;
for(int i = 0; i < n; ++i)
{
if(s[i] == s[pos])
{
if(i < n - 1 && s[i + 1] == str[x]) temp = min(temp, backtrack(i + 1, x + 1) + abs(pos - i) + 1);
if(i > 0 && s[i - 1] == str[x]) temp = min(temp, backtrack(i - 1, x + 1) + abs(pos - i) + 1);
}
}
return temp;
}
int main()
{
cin >> n >> m >> s >> str;
for(int i = 0; i < n; ++i) if(s[i] == str[0]) mini = min(mini, backtrack(i, 1));
if(mini < INT_MAX) cout << mini;
else cout << -1;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
212 KB |
Output is correct |
2 |
Correct |
1 ms |
212 KB |
Output is correct |
3 |
Correct |
1 ms |
256 KB |
Output is correct |
4 |
Correct |
1 ms |
212 KB |
Output is correct |
5 |
Correct |
1 ms |
300 KB |
Output is correct |
6 |
Correct |
1 ms |
212 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
1079 ms |
280 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |