1110 - An Easy LCS(LIGHT OJ)

I couldn't pass this problem (got TLE ) through top down approach  ( :(  ) you can try , i was able to

make it accepted through Bottom Up approach   ----------->




#include<bits/stdc++.h>
using namespace std;

//----------optimal string---------

string LCS(string a,string b)
{
    int al=a.length(),bl=b.length();
    if(al==bl)
    {
        if(a>b)
            return b;
        else
            return a;
    }
    else
    {
        if(al>bl)
            return a;
        else
            return b;
    }
}

//----------main function----------

int main()
{
    int T;
    string s1,s2,dp[103][103];
    scanf("%d",&T);
    for(int tt=1;tt<=T;tt++)
    {
        cin>>s1>>s2;
        int l1=s1.length();     int l2=s2.length();

        //-------------reset all----------

        for(int i=0;i<=l1;i++)
            dp[0][i].clear();
        for(int i=0;i<=l2;i++)
            dp[i][0].clear();

        string ns1="."+s1, ns2="."+s2;      //to fit string upto l1 and l2 length

        /*  matrix or dp table pattern
            ns1 goes along to the column
            ns2 goes along to the row

               n   s   1
           n
           s
           2
        */

        for(int i=1;i<=l2;i++)
        {
            for(int j=1;j<=l1;j++)
            {
                if(ns1[j]==ns2[i])
                {

                    dp[i][j]=dp[i-1][j-1]+ns1[j];
                }
                else
                {
                    string str=LCS(dp[i-1][j],dp[i][j-1]);
                    dp[i][j]=str;
                }
            }
        }
        printf("Case %d: ",tt);
        if(dp[l2][l1].length()==0)
        {
            printf(":(\n");
        }
        else
        {
            cout<<dp[l2][l1]<<endl;
        }
    }
    return 0;
}

Comments

Popular posts from this blog

PopIt Serially support page

10405 - Longest Common Subsequence (UVA)