#include <bits/stdc++.h>
using namespace std;
#ifndef _LOCAL
//#pragma GCC optimize("O3,Ofast")
#else
#pragma GCC optimize("O0")
#endif
template<typename t> inline void umin(t &a, const t b) {a = min(a, b);}
template<typename t> inline void umax(t &a, const t b) {a = max(a, b);}
typedef pair<int, int> pii;
typedef long long ll;
typedef long double ld;
ll time() {return chrono::system_clock().now().time_since_epoch().count();}
mt19937 rnd(time());
#define ft first
#define sd second
#define len(f) int((f).size())
#define bnd(f) (f).begin(), (f).end()
#define _ <<' '<<
const int inf = 1e9 + 5;
const ll inf64 = 4e18 + 5;
const int md = 998244353;
namespace MD {
void add(int &a, const int b) {if((a += b) >= md) a -= md;}
void sub(int &a, const int b) {if((a -= b) < 0) a += md;}
int prod(const int a, const int b) {return ll(a) * b % md;}
};
int n, m;
string s, t;
const int N = 303;
int f[N], g[N];
bool first;
void letter(char c) {
if(first) {
first = false;
for(int i = 0; i < n; ++i)
if(s[i] != c) f[i] = +inf;
return;
}
fill(g, g + n, +inf);
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
if(i != j && s[i] == s[j]) {
if(i)
umin(g[i - 1], 1 + f[j] + abs(i - j));
if(i + 1 < n)
umin(g[i + 1], 1 + f[j] + abs(i - j));
}
for(int i = 0; i < n; ++i) {
if(i) umin(g[i], f[i - 1] + 1);
if(i + 1 < n) umin(g[i], f[i + 1] + 1);
if(s[i] != c) g[i] = +inf;
}
memcpy(f, g, n << 2);
}
void solve() {
first = true;
cin >> n >> m >> s >> t;
memset(f, 0, n << 2);
for(char c : t) letter(c);
int ans = *min_element(f, f + n);
if(ans >= +inf) ans = -1;
cout << ans << endl;
}
int main() {
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#ifndef _LOCAL
// freopen("file.in", "r", stdin);
// freopen("file.out", "w", stdout);
#else
system("color a");
freopen("in.txt", "r", stdin);
int t; cin >> t;
while(t--)
#endif
solve();
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
364 KB |
Output is correct |
2 |
Correct |
0 ms |
364 KB |
Output is correct |
3 |
Correct |
0 ms |
364 KB |
Output is correct |
4 |
Correct |
0 ms |
364 KB |
Output is correct |
5 |
Correct |
1 ms |
364 KB |
Output is correct |
6 |
Correct |
1 ms |
364 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
57 ms |
364 KB |
Output is correct |
2 |
Correct |
58 ms |
364 KB |
Output is correct |
3 |
Correct |
41 ms |
384 KB |
Output is correct |
4 |
Correct |
44 ms |
364 KB |
Output is correct |
5 |
Correct |
3 ms |
364 KB |
Output is correct |
6 |
Correct |
4 ms |
364 KB |
Output is correct |
7 |
Correct |
54 ms |
364 KB |
Output is correct |
8 |
Correct |
67 ms |
364 KB |
Output is correct |
9 |
Correct |
104 ms |
364 KB |
Output is correct |
10 |
Correct |
2 ms |
364 KB |
Output is correct |
11 |
Correct |
54 ms |
396 KB |
Output is correct |