LightOj 1110 - An Easy LCS

// Header file begin
#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#include<string>
#include<vector>
#include<cmath>
#include<cctype>
#include<sstream>
#include<set>
#include<list>
#include<stack>
#include<utility>
#include<queue>
#include<algorithm>
#include<cstdlib>
#include<bitset>

#define to_fast ios_base::sync_with_stdio(0)
#define up 1
#define down -1
#define diag 0

using namespace std;

int b[105][105] , c[105][105] , chlen=0;
char ch[105];
string x, y , pre[105][105];

int LCS(int m , int n)
{
    int i , j;

    for(i=1; i<=m; i++)
    {
        c[i][0]=0;
    }

    for(j=0; j<=n; j++)
    {
        c[0][j]=0;
    }

    for(i=1; i<=m; i++)
    {
        for(j=1; j<=n; j++)
        {
            if(x[i-1] == y[j-1])
            {
                c[i][j] = c[i-1][j-1] + 1;
                b[i][j] = diag;
                pre[i][j] = pre[i-1][j-1] + x[i-1];
            }

            else if(c[i-1][j] > c[i][j-1])
            {
                c[i][j] = c[i-1][j];
                b[i][j] = up;
                pre[i][j] = pre[i-1][j];
            }

            else if(c[i-1][j] < c[i][j-1])
            {
                c[i][j] = c[i][j-1];
                pre[i][j] = pre[i][j-1];
            }

            else
            {
                c[i][j] = c[i][j-1];
                b[i][j] = down;
                pre[i][j] = min(pre[i-1][j] , pre[i][j-1]); // take the minimum string due to the  lexicographically smallest.
            }
        }
    }

    //cout << c[m][n] << "\n";

    return c[m][n];
}

int main()
{
    to_fast;

    int t , tc=0;
    cin >> t;
    while(t--)
    {
        cin >> x >> y;

        int xlen = x.length() ;
        int ylen = y.length();

        int r = LCS(xlen, ylen);

        cout << "Case " << ++tc << ": ";

        if(!r)
        {
            cout << ":(\n";
        }

        else
        {
            cout << pre[xlen][ylen] << "\n";
        }
    }

    return 0;
}

Comments

Popular posts from this blog

SPOJ-CMG - Collecting Mango

LightOJ 1009 - Back to Underworld

LeetCode Palindrome Number