Common Subsequence(最长公共子序列-LCS-简单模板题)
source:POJ 1458
Time Limit: 1000MS
Memory Limit: 10000K
描述
A
A
A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence
X
=
<
x
X = <x
X=<x1,
x
x
x2
,
.
.
.
,
x
, ..., x
,...,xm
>
>
> another sequence
Z
=
<
z
Z = <z
Z=<z1
,
z
, z
,z2
,
.
.
.
,
z
, ..., z
,...,zk
>
>
> is a subsequence of X if there exists a strictly increasing sequence
<
i
<i
<i1
,
i
, i
,i2
,
.
.
.
,
i
, ..., i
,...,ik
>
>
> of indices of
X
X
X such that for all
j
=
1
,
2
,
.
.
.
,
k
,
x
j = 1,2,...,k, x
j=1,2,...,k,xij
=
z
= z
=zj. For example,
Z
=
<
a
,
b
,
f
,
c
>
Z = <a, b, f, c>
Z=<a,b,f,c> is a subsequence of
X
=
<
a
,
b
,
c
,
f
,
b
,
c
>
X = <a, b, c, f, b, c>
X=<a,b,c,f,b,c> with index sequence
<
1
,
2
,
4
,
6
>
<1, 2, 4, 6>
<1,2,4,6>. Given two sequences
X
X
X and
Y
Y
Y the problem is to find the length of the maximum-length common subsequence of
X
X
X and
Y
Y
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
Sample Input
abcfbc abfcab
programming contest
abcd mnp
Sample Output
4
2
0
题意
给出两个字符串,找出两个字符串的最长公共字串(可以不连续)。
代码
#include <iostream>
#include <algorithm>
#include <string.h>
#define maxn 1005
#define inf 0x3f3f3f3f
#define ll long long
#define _for(i, a) for(ll i = 0; i < (a); i++)
#define _rep(i, a, b) for(ll i = (a); i <= (b); i++)
using namespace std;
char a[maxn], b[maxn];
int dp[maxn][maxn];
int main() {
while (cin >> a >> b) {
memset(dp, 0, sizeof(dp));
int an = strlen(a), bn = strlen(b);
_rep(i, 1, an) {
_rep(j, 1, bn) {
if (a[i - 1] == b[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
}
else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
cout << dp[an][bn] << "\n";
}
return 0;
}