[DP] Luogu P1279 string distance

Link

Insert picture description here


solution

Changing the meaning of the question, you can know:
· Extra spaces are useless
· A letter matches another string of letters or matches a space
· No aftereffect

f [ i ] [ j ] f[i][j] f [ i ] [ j ] is the minimum distance
DP equation after thefirst string has processed i and the second string has processed j:

f[i][j] = min{f[i-1][j]+k, f[i][j-1]+k, f[i-1][j-1]+abs(a[i]-b[j])}
//第一个串的字符匹空格,第二个串的字符匹空格,上下串字符匹配

Code

#include<cstdio>
#include<cmath>
#include<iostream>
#include<cstring>
using namespace std;
string a, b;
int n1, n2, k, w1[3000], w2[3000], f[3000][3000];
int main(){
    
    
	cin>>a>>b;	
	scanf("%d", &k);
	n1 = a.size(); n2 = b.size();
	for(int i = 1; i <= n1; ++i){
    
    
		w1[i] = a[i-1] - 96;
		f[i][0] = k * i;
	}
	for(int i = 1; i <= n2; ++i){
    
    
		w2[i] = b[i-1] - 96;
		f[0][i] = k * i;
	}
	f[0][0] = 0;
	for(int i = 1; i <= n1; ++i)
		for(int j = 1; j <= n2; ++j)
			f[i][j] = min(min(f[i-1][j] + k, f[i][j-1] + k), f[i-1][j-1]+abs(w1[i]-w2[j]));
	printf("%d", f[n1][n2]);
} 

Guess you like

Origin blog.csdn.net/qq_42937087/article/details/115026991