#include <bits/stdc++.h>
#define F first
#define S second
#define pb push_back
#define ppb pop_back
#define ep insert
#define endl '\n'
#define elif else if
#define pow pwr
#define sqrt sqrtt
#define int long long
typedef unsigned long long ull;
using namespace std;
const int N=305;
int dp[N][N],n,m;
char a[N],b[N];
bool vis[N][N];
vector<int> adj[30];
set<char> s;
int rec(int i,int j){
//cout<<i<<' '<<j<<endl;
if (j==m) return 0;
if (vis[i][j]) return dp[i][j];
vis[i][j]=true;
dp[i][j]=INT_MAX;
if (i>1){
if (a[i-1]==b[j+1]) dp[i][j]=min(dp[i][j],rec(i-1,j+1)+1);
}
if (i<n){
if (a[i+1]==b[j+1]) dp[i][j]=min(dp[i][j],rec(i+1,j+1)+1);
}
for (auto u:adj[a[i]-'a']) dp[i][j]=min(dp[i][j],rec(u,j)+abs(u-i));
return dp[i][j];
}
int32_t main(){
ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
cin>>n>>m;
for (int i=1;i<=n;i++){
cin>>a[i];
s.ep(a[i]);
adj[a[i]-'a'].pb(i);
}
for (int j=1;j<=m;j++) cin>>b[j];
if (s.size()==n){
int idx=0;
for(int i=1;i<=n;i++){
if(a[i]==b[1]) idx=i;
}
if(idx==0){
cout<<-1;
return 0;
}
int ans=0;
for(int i=2;i<=m;i++){
bool c=0;
if(idx+1<=m && a[idx+1]==b[i]){
ans++;
c=1;
idx++;
}
else if(idx-1>=1 && a[idx-1]==b[i]){
ans++;
c=1;
idx--;
}
if(!c){
cout<<-1;
return 0;
}
}
cout<<ans;
return 0;
}
int ans=INT_MAX;
for (int i=1;i<=n;i++) ans=min(ans,rec(i,0));
if (ans>=INT_MAX) cout<<-1<<endl;
else cout<<ans-1<<endl;
return 0;
}
Compilation message
bajka.cpp: In function 'int32_t main()':
bajka.cpp:44:17: warning: comparison of integer expressions of different signedness: 'std::set<char>::size_type' {aka 'long unsigned int'} and 'long long int' [-Wsign-compare]
44 | if (s.size()==n){
| ~~~~~~~~^~~
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
212 KB |
Output is correct |
2 |
Correct |
0 ms |
212 KB |
Output is correct |
3 |
Correct |
1 ms |
212 KB |
Output is correct |
4 |
Correct |
0 ms |
212 KB |
Output is correct |
5 |
Correct |
1 ms |
212 KB |
Output is correct |
6 |
Correct |
0 ms |
212 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
1108 KB |
Output is correct |
2 |
Correct |
6 ms |
1236 KB |
Output is correct |
3 |
Correct |
3 ms |
1236 KB |
Output is correct |
4 |
Correct |
3 ms |
1236 KB |
Output is correct |
5 |
Correct |
2 ms |
1108 KB |
Output is correct |
6 |
Correct |
1 ms |
1108 KB |
Output is correct |
7 |
Correct |
7 ms |
1108 KB |
Output is correct |
8 |
Correct |
26 ms |
1108 KB |
Output is correct |
9 |
Correct |
61 ms |
1212 KB |
Output is correct |
10 |
Correct |
1 ms |
1108 KB |
Output is correct |
11 |
Correct |
6 ms |
1108 KB |
Output is correct |