ZOJ 3603 DP LCS

已经5年没有做OJ了,

曾经沧海难为水,除去巫山不是云“

准备每周刷1-2题!

题目大意:给出N个字符串,且各个字符串都包含唯一的字母,即不存在“ABCA”(A重复了),而“AFDSG”是正确的。

                 求出N个字符串的公共字母。 最后,按照字典序输出。

分     析:首先对各个字符串进行字典序排序,然后求所有的LCS,做法是两两相求即可。N个字符串,总共求N-1次LCS,就得到最后的结果了。

代     码:

//http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3603
#include<iostream>
#include<stack>
#include<cstdio>
#include<algorithm>
#include<string>
#include<fstream>

using namespace std;

int matrix[14][14];
int f[14][14];

string result = "";
void subSequence(int i, int j, string str)
{
    if (i == 0 || j == 0) return;
    if (f[i][j] == 1)
    {
        result = str[i - 1] + result;
        subSequence(i - 1, j - 1, str);
    }
    else
    {
        if (f[i][j] == 2)
        {
            subSequence(i - 1, j, str);
        }
        else
        {
            subSequence(i, j - 1, str);
        }
    }
}


string LCS(string str1, string str2)
{
    //初始化边界,过滤掉0的情况
    for (int i = 0; i <= str1.size(); i++)
        matrix[i][0] = 0;

    for (int j = 0; j <= str2.size(); j++)
        matrix[0][j] = 0;

    for (int i = 0; i < 22; i++)
    {
        for (int j = 0; j < 22; j++)
        {
            f[i][j] = 0;
        }
    }

    //填充矩阵
    for (int i = 1; i <= str1.size(); i++)
    {
        for (int j = 1; j <= str2.size(); j++)
        {
            if (str1[i - 1] == str2[j - 1])
            {
                matrix[i][j] = matrix[i - 1][j - 1] + 1;
                f[i][j] = 1;
            }
            else
            {
                if (matrix[i - 1][j] >= matrix[i][j - 1])
                {
                    matrix[i][j] = matrix[i - 1][j];
                    f[i][j] = 2;
                }
                else
                {
                    matrix[i][j] = matrix[i][j - 1];
                    f[i][j] = 3;
                }
            }
        }
    }
    result = "";
    subSequence(str1.size(), str2.size(), str1);
    return result;
}


int main()
{
    //fstream cin("3603.txt");
    int T, n;
    cin >> T;
    while (T--)
    {
        cin >> n;
        stack<string> st = stack<string>();
        while (!st.empty())
        {
            st.pop();
        }

        string tmp;
        for (int i = 0; i < n; i++)
        {
            cin >> tmp;
            sort(tmp.begin(), tmp.end());

            if (!st.empty())
            {
                string inner = st.top();
                st.pop();
                st.push(LCS(inner, tmp));
            }
            else
            {
                st.push(tmp);
            }
        }
        cout << st.top() << endl;
    }
    return 0;
}

 

原文地址:https://www.cnblogs.com/pengzhen/p/4356451.html