• C++
  • 信奥1600--动态规划例题讲解

  • @ 2024-4-6 18:05:29

image image image image image image image

#include<bits/stdc++.h>
using namespace std;
const int N = 1e3+10;
char x[N],y[N];
int c[N][N],l_max=-1,p_max;
int main(){
	cin>>x>>y;
	for(int i=1;i<=strlen(x);i++){
		for(int j=1;j<=strlen(y);j++){
			if(x[i-1]!=y[j-1])c[i][j]=0;
			else{
				c[i][j]=c[i-1][j-1]+1;
				if(c[i][j]>l_max){
					l_max=c[i][j];
					p_max=i;
				}
			}
		}
	}
	cout<<l_max<<endl;
	for(int i=p_max-l_max+1;i<=p_max;i++){
		cout<<x[i-1];
	}
	return 0;
}

image image image image image image image image image image

#include<bits/stdc++.h>
using namespace std;
const int N = 1e3+10;
char s[N],t[N];
int d[N][N],rec[N][N];
int main(){
	cin>>s>>t;
//	求字符串的长度
	int n = strlen(s);
	int m = strlen(t);
//	初始化
	for(int i=1;i<=n;i++){
		d[i][0]=i;//把长度为i的串变为空串至少需要i次操作(删除)
		rec[i][0]=1;//记录达到本次的上一个位置(删除)
	}
	for(int j=1;j<=n;j++){
		d[0][j]=j;//把空串变成长度为j的字符串,至少需要j次操作,插入
		rec[0][j]=2;//插入
	}
//	递推计算
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			int c = 0;
			if(s[i-1]!=t[j-1])c=1;
			int a1 = d[i-1][j-1]+c;
			int a2 = d[i-1][j]+1;
			int a3 = d[i][j-1]+1;
			if(a1<min(a2,a3)){
				d[i][j]=a1;
				rec[i][j]=3;
			}else if(a2<min(a1,a3)){
				d[i][j]=a2;
				rec[i][j]=1;
			}else{
				d[i][j]=a3;
				rec[i][j]=2;
			}
		}
	}
	cout<<d[n][m]<<endl;
	while(rec[n][m]){
		if(rec[n][m]==2){
			cout<<"插入"<<t[m-1]<<endl;
			m--;
		}else if(rec[n][m]==1){
			cout<<"删除"<<s[n-1]<<endl;
			n--;
		}else{
			if(s[n-1]==t[m-1]){
				cout<<"无需操作"<<endl;
			}else cout<<"把"<<s[n-1]<<"替换为"<<t[m-1]<<endl;
			m--;
			n--;
		}
	}
	return 0;
}

1 条评论

  • @ 2024-4-13 9:02:26
    #include<bits/stdc++.h>
    using namespace std;
    const int N = 1e3+10;
    char s[N],t[N];
    int main(){
    	cin>>s>>t;
    	int n = strlen(s);
    	int m = strlen(t);
    	for(int i=1;i<=n;i++){
    		d[i][0]=i
    		rec[i][0]=1;
    	}
    	for(int j=1;j<=n;j++){
    		d[0][j]=j;
    		rec[0][j]=2;
    	}
    	for(int i=1;i<=n;i++){
    		for(int j=1;j<=m;j++){
    			int c = 0;
    			if(s[i-1]!=t[j-1])c=1;
    			int a1 = d[i-1][j-1]+c;
    			int a2 = d[i-1][j]+1;
    			int a3 = d[i][j-1]+1;
    			if(a1<min(a2,a3)){
    				d[i][j]=a1;
    				rec[i][j]=3;
    			}else if(a2<min(a1,a3)){
    				d[i][j]=a2;
    				rec[i][j]=1;
    			}else{
    				d[i][j]=a3;
    				rec[i][j]=2;
    			}
    		}
    	}
    	cout<<d[n][m]<<endl;
    	while(rec[n][m]){
    		if(rec[n][m]==2){
    			cout<<
    <<t[m-1]<<endl;
    			m--;
    		}else if(rec[n][m]==1){
    			cout<<"删除"<<s[n-1]<<endl;
    			n--;
    		}else{
    			if(s[n-1]==t[m-1]){
    				cout<<"无需操作"<<endl;
    			}else cout<<"把"<<s[n-1]<<"替换为"<<t[m-1]<<endl;
    			m--;
    			n--;
    		}
    	}
    	return 0;
    }
    
    • 1