解题笔记 之 1733 简单动态规划

http://acm.zju.edu.cn/show_problem.php?pid=1733

 

1733, 最大子串,标准 CLS算法,动态规划

 

那个记录二维数组可以静态分配的,不过无所谓了,测试数据很弱

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define max_int(a, b) ((a)>(b) ? (a) : (b))

int longest_common_seq(char* string_a, char* string_b);

int main(int argc, char** argv) {
    char string_a[1500], string_b[1500];
    freopen("in.txt", "r", stdin);
    while(scanf("%s %s", string_a, string_b) != EOF) {
        printf("%d\n", longest_common_seq(string_a, string_b));
    }
    
    return 0;
}

int longest_common_seq(char* a, char* b) {
    int length_a = strlen(a);
    int length_b = strlen(b);
    int i, j, max = 0;

    int** comp_matrix = (int**)malloc((1 + length_b)*sizeof(int*));
    for(i = 0; i <= length_b; i ++) {
        comp_matrix[i] = (int*)malloc((1 + length_a)*sizeof(int));
    }

    for(i = 0; i <= length_b; i++) comp_matrix[i][0] = 0;
    for(i = 0; i <= length_a; i++) comp_matrix[0][i] = 0;

    for(i = 1; i <= length_a; i ++) {
        for(j = 1; j <= length_b; j ++) {
            if(a[i - 1] == b[j - 1]) {
                comp_matrix[j][i] = comp_matrix[j - 1][i - 1] + 1;
            } else {
                comp_matrix[j][i] = max_int(comp_matrix[j - 1][i], comp_matrix[j][i - 1]);
            }
            
            max = max_int(max, comp_matrix[j][i]);
        }
    }

    return max;
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值