Problem Description
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.
(问题描述
给定序列的子序列是省略了一些元素(可能没有)的给定序列。给定序列X = 另一个序列Z = 是X的子序列,如果存在严格递增序列< i1,i2,…这样对于所有的j = 1,2,…,k,xij = zj。例如,Z = 是X = 的子序列,索引序列< 1,2,4,6 >。给定两个序列X和Y,问题是找到X和Y的最大长度公共子序列的长度
程序输入来自文本文件。文件中的每个数据集包含两个代表给定序列的字符串。序列由任意数量的空格分隔。输入数据正确。对于每组数据,程序在标准输出上打印从单独一行开始的最大长度公共子序列的长度。)
Sample Input(样本值输入)
abcfbc abfcab
programming contest
abcd mnp
Sample Output(抽样输出)
4
2
0
#include <iostream>
#include "string"
#include "algorithm"
using namespace std;
int ch[10001][10001];
string s1,s2; // 定义两个字符串
int length1,length2;
int main() {
while (cin >> s1 >> s2){
length1 = s1.length();
length2 = s2.length();
for (int i = 0; i <= length1; ++i) {
for (int j = 0; j <= length2; ++j) { // 循环两个字符串。
if (i == 0 || j == 0)
{
ch[i][j] = 0; // 若两个字符串为零,则最长的公共子序列为0。
continue;
}
if (s1[i - 1] == s2[j - 1])
ch[i][j] = ch[i - 1][j - 1] + 1; // 若两个字符串长度相等,则在两个字符串横竖构成的二维平面中,此为坐标点
else
ch[i][j] = max(ch[i - 1][j],ch[i][j - 1]); // 带入得到两个坐标,选择最大的一个为下个坐标点。
}
}
cout << ch[length1][length2] << endl;
}
cout << "Hello, World!" << endl;
return 0;
}