【POJ-1458】Common Subsequence

120 阅读1分钟
题意

给两个字符串,找到其中最长的公共子序列,输出长度.

 

样例
Sample Input
abcfbc         abfcab
programming    contest 
abcd           mnp


Sample Output
4
2
0

 



 

AC代码

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<math.h>

using namespace std;
//数组的声明给如果不是全局的或者static的, 会造成内存泄漏
//报错信息 :  Process returned -1073741571 (0xC00000FD)
char a[1000],b[1000];
int temp[1000][1000];
int main()
{
	int i, j, A_len, B_len;
	while(scanf("%s %s", a,b)!=EOF)
	{
        memset(temp, 0, sizeof(temp));

        A_len = strlen(a);
        B_len = strlen(b);
        for (i = 1; i <= A_len; i++) {
            for (j = 1; j <= B_len; j++) {
                if (a[i - 1] == b[j - 1])
                    temp[i][j] = temp[i - 1][j - 1] + 1;
                else
                    temp[i][j]=max(temp[i-1][j],temp[i][j-1]);
            }
        }
        cout<<temp[A_len][B_len]<<endl;
	}
	return 0;
}

 

题源:poj.org/problem?id=…