Common Subsequence
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.
Sample Input
abcfbc abfcab
programming contest
abcd mnp
Sample Output
4
2
0
Source
Recommend
Ignatius
题目类型:线性DP
算法分析:最长公共子序列的模板题,直接求解即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
#include <set> #include <bitset> #include <list> #include <map> #include <stack> #include <queue> #include <deque> #include <string> #include <vector> #include <ios> #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <algorithm> #include <utility> #include <complex> #include <numeric> #include <functional> #include <cmath> #include <ctime> #include <climits> #include <cstdarg> #include <cstdio> #include <cstdlib> #include <cstring> #include <cctype> #include <cassert> using namespace std; const int INF = 0x7FFFFFFF; const int MOD = 7; const double EPS = 1e-10; const double PI = 2 * acos (0.0); const int maxn = 2000 + 66; int dp[maxn][maxn]; char sa[maxn], sb[maxn]; int main() { // ifstream cin ("aaa.txt"); // freopen ("aaa.txt", "r", stdin); while (cin>> (sa + 1) >> (sb + 1)) { int lena = strlen (sa + 1), lenb = strlen(sb + 1); for (int i = 0; i <= lena; i++) dp[i][0] = 0; for (int i = 0; i <= lenb; i++) dp[0][i] = 0; for (int i = 1; i <= lena; i++) { for(int j = 1; j <= lenb; j++) { if (sa[i] == sb[j]) dp[i][j] = dp[i-1][j-1] + 1; else dp[i][j] = max (dp[i-1][j], dp[i][j-1]); } } cout << dp[lena][lenb] << endl; } return 0; } |
- « 上一篇:hdu1114
- hdu1160:下一篇 »