1.最长公共子序列

参考博客:

http://blog.csdn.net/hrn1216/article/details/51534607

http://blog.csdn.net/u013074465/article/details/45392687

代码:

#include <stdio.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <vector>
#include <set>
#include <stack>
#include <queue>
#include <algorithm>
#include <map>


#define I scanf
#define OL puts
#define O printf
#define F(a,b,c) for(a=b;a<c;a++)
#define FF(a,b) for(a=0;a<b;a++)
#define FG(a,b) for(a=b-1;a>=0;a--)
#define LEN 101
#define MAX 1<<30
#define V vector<int>

using namespace std;

int a[LEN],b[LEN]; 
int dp[LEN][LEN];
int N,M;
vector<vector<int> > ans;

void printDP(){
    int i,j;
    F(i,1,N+1){
        F(j,1,M+1){
            O("%d\t",dp[i][j]);
        }
        OL("\n");
    }
}

void buildLCS(int x,int y,V vec){
    while(x>0 && y>0){
        if(a[x]==b[y]){
            vec.push_back(a[x]);
            x--;y--;
        }else{
            if(dp[x-1][y]>dp[x][y-1]){
                x--;
            }else if(dp[x-1][y]<dp[x][y-1]){
                y--;
            }else{
                buildLCS(x,y-1,vec);
                x--;
            }
        }
    }
    int i=vec.size()-1;
    while(i>=0){
        O("%d ",vec[i]);
        i--;
    }
    OL("");
}

int main(){
    freopen("LCS.txt","r",stdin);
    int i,j;
    scanf("%d",&N);
    F(i,1,N+1) I("%d",&a[i]);
    scanf("%d",&M);
    F(i,1,M+1) I("%d",&b[i]);
    F(i,1,N+1){ 
        F(j,1,M+1){
            if(a[i]==b[j])
                dp[i][j]=dp[i-1][j-1]+1;
            else
                dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
        }
    }
    printDP();
    O("最长公共子序列长度: %d\n",dp[N][M]);
    V vec;
    buildLCS(N,M,vec);
    return 0;
}
View Code

相关文章:

  • 2021-11-20
  • 2021-06-16
  • 2021-08-06
  • 2021-04-20
  • 2021-11-15
  • 2021-11-04
  • 2021-07-19
  • 2021-09-17
猜你喜欢
  • 2021-06-16
  • 2022-01-16
  • 2021-05-24
  • 2021-12-08
  • 2021-07-15
  • 2022-01-28
  • 2022-12-23
相关资源
相似解决方案