Common Subsequence HDU 1159 最长公共子序列Longest Common Subsequence,LCS

A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = <x1, x2, ..., xm> another sequence Z = <z1, z2, ..., zk> is a subsequence of X if there exists a strictly increasing sequence <i1, i2, ..., ik> of indices of X such that for all j = 1,2,...,k, xij = zj. For example, Z = <a, b, f, c> is a subsequence of X = <a, b, c, f, b, c> with index sequence <1, 2, 4, 6>. Given two sequences X and Y the problem is to find the length of the maximum-length common subsequence of X and Y. 
The program input is from a text file. Each data set in the file contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct. For each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line. 

Input

abcfbc abfcab
programming contest 
abcd mnp

Output

4
2
0
就一模板
if Xi=Yi,fnid the LCS of Xi-1 and Yi-1;
else{
  if(Xi==Yj)L[i][j]=L[i-1][j-1]+1;
  else L[i][j]=max(L[i][j-1],L[i-1][j]);
}
还是打伪代码比打字快(逃
//#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <cmath>
#include<cstring>
#include <algorithm>
#include <queue>
#include<map>
using namespace std;
typedef long long ll;
const ll inf = 1e13;
const int mod = 1000000007;
const int mx = 1005; //check the limits, dummy
typedef pair<int, int> pa;
const double PI = acos(-1);
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
#define swa(a,b) a^=b^=a^=b
#define re(i,a,b) for(int i=(a),_=(b);i<_;i++)
#define rb(i,a,b) for(int i=(b),_=(a);i>=_;i--)
#define clr(a) memset(a, 0, sizeof(a))
#define lowbit(x) ((x)&(x-1))
#define mkp make_pai
//void sc(int& x) { scanf("%d", &x); }void sc(int64_t& x) { scanf("%lld", &x); }void sc(double& x) { scanf("%lf", &x); }void sc(char& x) { scanf(" %c", &x); }void sc(char* x) { scanf("%s", x); }
int n, m, k,ans[mx];
int dp[mx][mx];
string s1, s2;
int LCS() {
    clr(dp);
    re(i, 1, s1.length()+1)
        re(j, 1, s2.length()+1) {
        if (s1[i - 1] == s2[j - 1])
            dp[i][j] = dp[i - 1][j - 1] + 1;
        else
            dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
    }
    return dp[s1.length()][s2.length()];
}
int main()
{
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    while (cin>>s1>>s2)
    {
        cout << LCS() << endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/xxxsans/p/12741507.html