zoukankan      html  css  js  c++  java
  • Vijos 1111 小胖的水果 LCS

    描述

    xuzhenyi到大同水果店去买水果,但老板huyichen告诉他每次只能买一种,但是xuzhenyi想吃两种,于是在讨价还价之后,huyichen说只要xuzhenyi能把他想要的两种水果合并成一种,就能成功。你能帮他吗?

    格式

    输入格式

    输入文件包含两个要组合的水果名字。所有的名字最多有100个字母。(有若干行)

    输出格式

    对每一组测试数据,打印出一个最短的组合长度.

    样例1

    样例输入1

    apple peach
    ananas banana
    pear peach

    样例输出1

    8
    7
    6

    题解

    这是一道有关“最长公共子序列”的题。由题意不难看出:
    假设两个字符串s和t的长度分别为n和m,则答案即为:
    n+m-{s和t的最长公共子序列的长度}

    代码:

    #include <iostream>
    #include <cstring>
    using namespace std;
    const int maxn = 110;
    int f[maxn][maxn], n, m;
    char s[maxn], t[maxn];
    int main()
    {
        while (cin >> s >> t)
        {
            memset(f, 0, sizeof(f));
            n = strlen(s);
            m = strlen(t);
            f[0][0] = s[0] == t[0];
            for (int i = 1; i < n; i ++)
                f[i][0] = max(f[i-1][0], (int)(s[i] == t[0]));
            for (int i = 1; i < m; i ++)
                f[0][i] = max(f[0][i-1], (int)(s[0] == t[i]));
            for (int i = 1; i < n; i ++)
            {
                for (int j = 1; j < m; j ++)
                {
                    f[i][j] = max(f[i][j-1], f[i-1][j]);
                    if (s[i] == t[j])
                    {
                        f[i][j] = max(f[i][j], f[i-1][j-1]+1);
                    }
                }
            }
            cout << n + m - f[n-1][m-1] << endl;
        }
        return 0;
    }
    
    
  • 相关阅读:
    Geometry
    后缀数组dc3算法模版(待补)
    CodeForces 467D(267Div2-D)Fedor and Essay (排序+dfs)
    HDU 3572 Task Schedule (最大流)
    Acdream手速赛7
    hdu2732 Leapin' Lizards (网络流dinic)
    HDU 3549 Flow Problem (最大流ISAP)
    HDU 1532 Drainage Ditches (网络流)
    [容易]合并排序数组 II
    [容易]搜索插入位置
  • 原文地址:https://www.cnblogs.com/xianyue/p/7082778.html
Copyright © 2011-2022 走看看