#include<bits/stdc++.h>
#define pb push_back
#define fi first
#define se second
#define mp make_pair
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef long double ld;
template <typename T> bool chkmin(T &x,T y){return x>y?x=y,1:0;}
template <typename T> bool chkmax(T &x,T y){return x<y?x=y,1:0;}
int readint(){
int x=0,f=1; char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int n,m,dp[305][2];
char s[305],t[305];
int main(){
n=readint(); m=readint();
scanf("%s",s+1);
scanf("%s",t+1);
for(int i=1;i<=n;i++) dp[i][0]=(s[i]==t[1]?0:1e9),dp[i][1]=1e9;
for(int j=2;j<=m;j++){
for(int i=1;i<=n;i++){
if(i>1&&s[i-1]==t[j]) dp[i-1][1]=min(dp[i-1][1],dp[i][0]+1);
if(i<n&&s[i+1]==t[j]) dp[i+1][1]=min(dp[i+1][1],dp[i][0]+1);
}
for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(s[i]==s[j]) dp[j][1]=min(dp[j][1],dp[i][1]+abs(i-j));
for(int i=1;i<=n;i++) dp[i][0]=dp[i][1],dp[i][1]=1e9;
}
int ans=1e9;
for(int i=1;i<=n;i++) ans=min(ans,dp[i][0]);
if(ans==1e9) printf("-1\n"); else printf("%d\n",ans);
return 0;
}
Compilation message
bajka.cpp: In function 'int main()':
bajka.cpp:31:7: warning: ignoring return value of 'int scanf(const char*, ...)' declared with attribute 'warn_unused_result' [-Wunused-result]
31 | scanf("%s",s+1);
| ~~~~~^~~~~~~~~~
bajka.cpp:32:7: warning: ignoring return value of 'int scanf(const char*, ...)' declared with attribute 'warn_unused_result' [-Wunused-result]
32 | scanf("%s",t+1);
| ~~~~~^~~~~~~~~~
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
348 KB |
Output is correct |
2 |
Correct |
0 ms |
348 KB |
Output is correct |
3 |
Correct |
0 ms |
348 KB |
Output is correct |
4 |
Correct |
0 ms |
436 KB |
Output is correct |
5 |
Correct |
0 ms |
348 KB |
Output is correct |
6 |
Correct |
1 ms |
348 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
31 ms |
344 KB |
Output is correct |
2 |
Correct |
35 ms |
668 KB |
Output is correct |
3 |
Correct |
30 ms |
344 KB |
Output is correct |
4 |
Correct |
34 ms |
344 KB |
Output is correct |
5 |
Correct |
2 ms |
348 KB |
Output is correct |
6 |
Correct |
2 ms |
348 KB |
Output is correct |
7 |
Correct |
34 ms |
436 KB |
Output is correct |
8 |
Correct |
37 ms |
348 KB |
Output is correct |
9 |
Correct |
32 ms |
348 KB |
Output is correct |
10 |
Correct |
1 ms |
348 KB |
Output is correct |
11 |
Correct |
31 ms |
440 KB |
Output is correct |