矩阵连乘问题
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e2+10;
int n;
int m[N][N];
int s[N][N];
int p[N];
void kuohao(int a,int b){
if(a==b)
return ;
kuohao(a,s[a][b]);
kuohao(s[a][b]+1,b);
cout<<"multiply "<<"A"<<a<<","<<s[a][b]<<" and "<<"A"<<s[a][b]+1<<","<<b<<endl;
}
int main(){
cout<<"请输入连乘矩阵个数:"<<endl;
cin>>n;
cout<<"请输入矩阵的各维数:"<<endl;
for(int i=0;i<=n;i++){
cin>>p[i];
m[i][i]=0;
}
for(int r=2;r<=n;r++){
for(int i=1;i<=n-r+1;i++){
int j=i+r-1;
m[i][j]=INT_MAX;
for(int k=i;k<j;k++){
if(m[i][j]>m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j]){
m[i][j]=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j];
s[i][j]=k;
}
}
}
}
cout<<"最优解:"<<m[1][n]<<endl;
cout<<"最优划分方法:"<<endl;
kuohao(1,n);
}
LCS问题
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e2+10;
const int MAXN=N;
string s,s1,s2;
int LCSlength(string &s,string &s1,vector<vector<int>> &c,vector<vector<int>> &b){
int len1=s.length();
int len2=s1.length();
if(s==""&&s1=="")
return 0;
for(int i=0;i<=len1;i++){
c[i][0]=0;
}
for(int i=0;i<=len2;i++){
c[0][i]=0;
}
for(int i=1;i<=len1;i++){
for(int j=1;j<=len2;j++){
if(s[i-1]==s1[j-1]){
c[i][j]=c[i-1][j-1]+1;
b[i][j]=1;
}else if(c[i-1][j]>=c[i][j-1]){
c[i][j]=c[i-1][j];
b[i][j]=2;
}else if(c[i][j-1]>c[i-1][j]){
c[i][j]=c[i][j-1];
b[i][j]=3;
}
}
}
return c[len1][len2];
}
void printOneLCS(int len1,int len2,string &s,vector<vector<int>> &b){
if(len1==0||len2==0)
return ;
if(b[len1][len2]==1){
printOneLCS(len1-1,len2-1,s,b);
cout<<s[len1-1]<<" ";
}else if(b[len1][len2]==2){
printOneLCS(len1-1,len2,s,b);
}else if(b[len1][len2]==3){
printOneLCS(len1,len2-1,s1,b);
}
}
void printAllLCS(int ){
}
int main(){
cin>>s>>s1;
vector<vector<int>> b(s.length()+1,vector<int>(s1.length()+1));
vector<vector<int>> c(s.length()+1,vector<int>(s1.length()+1));
int len=LCSlength(s,s1,c,b);
cout<<"最长子序列的长度为:"<<len<<endl;
printOneLCS(s.length(),s1.length(),s,b);
cout<<endl;
}