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; }