The best includes the 10th Blue Bridge Cup National Competition C/C++ Group B

We say that a string S contains a string T, which means that T is a subsequence of S, that is, several characters can be extracted from the string S, and they are combined into a new string in the original order, which is exactly the same as T.

Given two strings S and T, how many characters in S can be modified at least so that S can contain T?

Input format
Enter two lines, one string per line.

The string in the first line is S, and the string in the second line is T.

Both strings are non-empty and only contain uppercase English letters.

Output format
Output an integer to indicate the answer.

Data range
1≤|T|≤|S| ≤1000
Input example:
ABCDEABCD
XAABZ
Output example:
3

Idea :
Consider dp, dp[i][j] represents the first i characters in the S string, including the first j characters in the T string, at least the number of characters that needs to be modified .
It is easy to know that dp[i][0]=0 0<=i<=len(S)
Next consider the transition state.

1. If s[i]=t[j], then the last digit in the t string will either make it equal to s[i] or make it equal to the previous one.
So dp[i][j]=min(dp[i-1][j],dp[i-1][j-1])

2. If s[i]!=t[j], then either make t[j] the same as the character before the s string, or modify s[i].
So dp[i][j]=min(dp[i-1][j],dp[i-1][j-1]+1)

#include<bits/stdc++.h>
using namespace std;
const int N=1e3+50;
char a[N],b[N];
int dp[N][N];
int main(){
    
    
    cin>>a+1>>b+1;
    int la=strlen(a+1);
    int lb=strlen(b+1);
    memset(dp,63,sizeof dp);
    dp[0][0]=0;
    for(int i=1;i<=la;i++){
    
    
        dp[i][0]=0;
        for(int j=1;j<=lb;j++){
    
    
            if(a[i]==b[j]) dp[i][j]=min(dp[i-1][j],dp[i-1][j-1]);
            else dp[i][j]=min(dp[i-1][j],dp[i-1][j-1]+1);
        }
    }
    cout<<dp[la][lb];
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_43563669/article/details/109676914