LightOJ 1110 An Easy LCS

来源:互联网 发布:进销存软件排行 编辑:程序博客网 时间:2024/05/16 01:23

LightOJ 1110 An Easy LCS


LCS means ‘Longest Common Subsequence’ that means two non-empty strings are given; you have to find the Longest Common Subsequence between them. Since there can be many solutions, you have to print the one which is the lexicographically smallest. Lexicographical order means dictionary order. For example, ‘abc’ comes before ‘abd’ but ‘aaz’ comes before ‘abc’.

Input
Input starts with an integer T (≤ 100), denoting the number of test cases.

Each case starts with a blank line. The next two lines will contain two strings of length 1 to 100. The strings contain lowercase English characters only.

Output
For each case, print the case number and the lexicographically smallest LCS. If the LCS length is 0 then just print ‘:(‘.

Sample Input Output for Sample Input 3 ab

ba Case 1: a zxcvbn

hjgasbznxbzmx Case 2: zxb you

kjhs Case 3: :(

求解最长公共子序列问题

序列str1和序列str2

+长度分别为m和n;
+创建1个二维数组L[m.n];
+初始化L数组内容为0
+m和n分别从0开始,m++,n++循环:
+如果str1[m] == str2[n],则L[m,n] = L[m - 1, n -1] + 1;
+如果str1[m] != str2[n],则L[m,n] = max{L[m,n - 1],L[m - 1, n]}
+最后从L[m,n]中的数字一定是最大的,且这个数字就是最长公共子序列的长度
+从数组L中找出一个最长的公共子序列


#include<iostream>#include <cstdio>#include <string.h>#include <cstring>using namespace std;int main(){#ifndef  ONLINE_JUDGE    freopen("1.txt","r",stdin);  #endif    int t, i, j, lena, lenb, m, count = 0;    char a[110], b[110];    string ans[110][110];    cin >> t;    while(t--)    {        scanf("%s%s", a + 1, b + 1);        lena = strlen(a + 1);        lenb = strlen(b + 1);        for (i = 1; i <= lena; i++)        {            for (j = 1; j <= lenb; j++)            {                ans[i][j] = "";            }        }        for(i = 1; i <= lena; i++)        {            for (j = 1; j <= lenb; j++)            {                if (a[i] == b[j])                {                    ans[i][j] = ans[i - 1][j - 1] + a[i];                }                else                {                    if (ans[i - 1][j].size() > ans[i][j - 1].size())                    {                        ans[i][j] = ans[i - 1][j];                    }                    else if (ans[i - 1][j].size() < ans[i][j - 1].size())                    {                        ans[i][j] = ans[i][j - 1];                    }                    else                    {                        ans[i][j] = (ans[i][j - 1] > ans[i - 1][j] ? ans[i - 1][j] : ans[i][j - 1]);                    }                }            }        }        printf("Case %d: ", ++count);        if(ans[lena][lenb].size())        {            cout << ans[lena][lenb] << endl;        }        else        {             puts(":(");        }    }    return 0;} 
0 0
原创粉丝点击