最长公共子序列 南工36

来源:互联网 发布:微量氧分析仪 淘宝 编辑:程序博客网 时间:2024/06/05 16:51

题目链接:here~~

比较第一个串s1的第i个字符与串s2的第j个字符是否相等,如果相等:res[i][j]=res[i-1][j-1]+1;(前i个串s1的字符和前j个串s2的字符的最长公共子序列长度=前i-1个串s1的字符和前j-1个串s2的字符的最长公共子序列长度+1);如果不相等:res[i][j]=max(res[i-1][j], res[i][j-1]);(前i个串s1的字符和前j个串s2的字符的最长公共子序列长度=max(前i-1个串s1的字符和前j个串s2的字符的最长公共子序列长度,前i个串s1的字符和前j-1个串s2的字符的最长公共子序列长度)

#include <cstring>#include <cstdio>#include <string.h>#define max(a, b) a>b?a:bint res[1001][1001];char s1[1001], s2[1001];int main(){    int n, i, j, l1,l2;    scanf("%d", &n);    while (n--)    {        scanf("%s%s", s1, s2);        l1=strlen(s1);        l2=strlen(s2);        memset(res, 0, sizeof(res));        for (i=1; i<=l1; i++)        {            for (j=1; j<=l2; j++)            {                if (s1[i-1]==s2[j-1])                    res[i][j]=res[i-1][j-1]+1;                else                    res[i][j]=max(res[i-1][j], res[i][j-1]);            }        }        printf("%d\n", res[l1][l2]);    }    return 0;}


原创粉丝点击