【UVA】531-Compromise(最长公共子串)

本文介绍了一种解决最长公共子串问题的算法实现,通过动态规划的方法找出两个字符串数组间的最长公共子串,并提供了完整的C++代码示例。

最长公共子串的问题,只不过单位从字符变成字符串了。

没什么好说的了~

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<map>
#include<stack>
#include<queue>
#include<set>
#include<ctime>
#include<cmath>
#include<string>
#include<iomanip>
#include<climits>
#include<cctype>
#include<deque>
#include<list>
#include<sstream>
#include<vector>
#include<cstdlib>
using namespace std;
#define _PI acos(-1.0)
#define INF (1 << 30)
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> pill;
/*================================================
================================================*/
#define MAXD 100 + 10
#define LEN 30 + 10
char txt1[MAXD][LEN];
char txt2[MAXD][LEN];
int size_1;
int size_2;
int dp[MAXD][MAXD];
void print(int n,int pos1,int pos2){
    if(n < 0)
        return ;
    for(int i = pos1 ; i >= 1; i--)
        for(int j = pos2 ; j >= 1; j--)
            if(strcmp(txt1[i],txt2[j]) == 0 && dp[i][j] == n){
                print(n - 1,i,j);
            if(n == dp[size_1][size_2])
            printf("%s",txt1[i]);
            else
            printf("%s ",txt1[i]);
            return ;
        }
}
void DP(){
    memset(dp,0,sizeof(dp));
    for(int i = 1 ; i <= size_1 ; i++)
        for(int j = 1 ; j <= size_2 ; j++){
            if(strcmp(txt1[i],txt2[j]) == 0)
                dp[i][j] = max(dp[i][j],dp[i - 1][j - 1] + 1);
            else
                dp[i][j] = max(dp[i - 1][j],dp[i][j - 1]);
        }
    print(dp[size_1][size_2],size_1,size_2);
    printf("\n");
}
int main(){
    size_1 = 1;
    size_2 = 1;
    while(scanf("%s",txt1[size_1]) != EOF){
         size_1 ++;
         while(scanf("%s",txt1[size_1])){
              if(txt1[size_1][0] == '#'){
                 size_1--;
                 break;
              }
              else
                size_1++;
         }
         while(scanf("%s",txt2[size_2])){
              if(txt2[size_2][0] == '#'){
                 size_2--;
                 break;
              }
              else
                size_2++;
         }
         DP();
         size_1 = 1;
         size_2 = 1;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值