Common Subsequence (动态规划)

最长公共子序列

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, x ij = 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.


Input The program input is from the std input. Each data set in the input contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct. Output 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. Sample Input

abcfbc         abfcab
programming    contest 
abcd           mnp

Sample Output

4
2
0

题解:

1.c[i][j]代表Xi和Yi的最长公共子序列

2.也就是同时遍历X和Y俩个字符串,i 遍历 X, j 遍历 Y;

3.若Xi == Yj,c[i][j] = c[i-1][j-1] + 1;

4.若Xi != Yj, c[i][j] = max(c[i][j-1], c[i-1][j]);

 

 1 #include<iostream>
 2 #include<cstring>
 3 #include<algorithm>
 4 using namespace std;
 5 
 6 int num[1000];
 7 int maxlen[1000];
 8 int main() {
 9     int N;
10     cin >> N;
11     for(int i = 0; i < N; i++) {
12         cin >> num[i];
13         maxlen[i] = 1;
14     }
15     //以第i个整数为终点,求其的最长子序列,遍历0-i的整数,若小于num[i],则用maxlen[j]+1与maxlen[i]取最大值赋值给maxlen[j] 
16     for(int i = 1; i < N; i++) {
17         for(int j = 0; j < i; j++) {
18             if(num[i] > num[j]) {
19                 maxlen[i] = max(maxlen[i], maxlen[j] + 1);
20             }
21         }
22     }
23     
24     cout << * max_element(maxlen, maxlen + N);
25     return 0;
26 } 

 

posted @ 2020-04-07 13:11  Mr__wei  阅读(370)  评论(0编辑  收藏  举报