Cod sursa(job #2078910)

Utilizator RazorBestPricop Razvan Marius RazorBest Data 30 noiembrie 2017 11:48:39
Problema Subsir Scor 50
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.74 kb
#include <fstream>
#include <iostream>
#include <cstring>
using namespace std;

ifstream fin("subsir.in");
ofstream fout("subsir.out");

int a[502][502], b[502][502];
int n1, n2;
char s1[501], s2[502], aux[2];

void init(int a[][502], int n1, int n2, int val)
{
    for (int i = 0; i <= n1; i++)
        a[i][0] = val;

    for (int i = 0; i <= n2; i++)
        a[0][i] = val;
}

int LCS()
{
    for (int i = 1; i <= n1; i++)
    {
        for (int j = 1; j <= n2; j++)
        {
            if (s1[i - 1] == s2[j - 1])
                a[i][j] = a[i - 1][j - 1] + 1;
            else
                a[i][j] = max(a[i - 1][j], a[i][j - 1]);
        }
    }

    return a[n1][n2];
}

int num()
{
    init(b, n1, n2, 1);

    for (int i = 1; i <= n1; i++)
        for (int j = 1; j <= n2; j++)
        {
            if (s1[i - 1] == s2[j - 1])
                b[i][j] = b[i - 1][j - 1];
            else if (a[i - 1][j - 1] == a[i - 1][j] && a[i - 1][j - 1] == a[i][j - 1])
                b[i][j] = b[i - 1][j] + b[i][j - 1] - b[i - 1][j - 1];
            else if (a[i - 1][j] == a[i][j - 1])
            {
                b[i][j] = b[i - 1][j] + b[i][j - 1];
            }
            else if (a[i - 1][j] > a[i][j - 1])
                b[i][j] = b[i - 1][j];
            else
                b[i][j] = b[i][j - 1];
        }
    return b[n1][n2];
}

void afis_mat(int a[][502], int n, int m)
{
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
            fout << a[i][j] << ' ';
        fout << '\n';
    }
}

int main()
{
    fin.get(s1, 501);
    fin.get(aux, 2, ' ');
    fin.get(s2, 501);

    n1 = strlen(s1);
    n2 = strlen(s2);

    LCS();
    fout << num();
}