分类:
2009-11-07 14:51:46
最长公共子序列(Longest Common Subsequence)
http://blog.csdn.net/hhygcy/archive/2009/03/02/3948969.aspx
问题描述:
注意这个问题是Subsequence不是Substring。substring的话就是子串,子串的要求的连续相等 的字符序列,而subsequence不要求连续。比如说ABCD和ABD。他们的longest common subsequence就是ABD。而Longest common substring就是AB
DP算法:
我们把问题分成两种情况来讨论:
1. 如果S1[i] == S2[j]。就是i,j对应位置上的字符相等。那么可以得出M[i,j] = M[i-1,j-1]+1;为什么呢?可以想象的。如果M[i-1,j-1]也是一个最后方案,在这个最优方案上我们同时增加一个字符。而这两个字符又相 等。那么我们只需要在这个M[i-1,j-1]的最优方案上++就可以了。
2. 如果S1[i] != S2[j]。那么就拿M[i-1,j]和M[i,j-1]来比较。M[i,j]的值就是M[i-1,j]和M[i,j-1]中大的值。这好比原来的字符串 是S1[1...i-1]是ABC,S2[1...j-1]是ABE。那S1[1..i]是ABCE,S2[1..j]是ABEC。可以看出来这个时候 M[i,j]不是由M[i-1,j-1]决定的,而是由ABCE和ABE或者ABC和ABEC来决定的,也就是M[i-1,j]和M[i,j-1]。
所以我们可以把这个问题的递归式写成:
实现:
#include <stdio.h>
#include <assert.h>
#include <string.h>
template <typename T>
T max(T const & a, T const & b)

{
return a>b?a:b;
}
//最长公共子序列(Longest Common Subsequence)
int c[100][100];
int n1;
char x[100];
int n2;
char y[100];
//compute C[i][j]
int C( int i, int j)

{
if (i<0 || j<0)
return 0;
if(c[i][j]>=0)
return c[i][j];
if(x[i] == y[j])
c[i][j] = C(i-1, j-1) + 1;
else
c[i][j] = max(C(i, j-1), C(i-1, j));
return c[i][j];
}
void main()

{
for(int i=0; i<100*100;i++)
c[i/100][i%100] = -1;
printf("Input string 1:\n");
scanf("%s", x);
n1 = strlen(x);
printf("Input string 2:\n");
scanf("%s", y);
n2 = strlen(y);
printf("LCS is: %d", C(n1-1,n2-1));
printf("matrix c:\n");
for(int i=0; i<n1; i++)
{
for(int j=0; j<n2; j++)
printf("%d ", c[i][j]);
printf("\n");
}
}
最长递增子序列(Longest Increase Subsequence)
http://blog.csdn.net/hhygcy/archive/2009/03/02/3950158.aspx
问题描述:
这里subsequence表明了这样的子序列不要求是连续的。比如说有子序列{1, 9, 3, 8, 11, 4, 5, 6, 4, 19, 7, 1, 7 }这样一个字符串的的最长递增子序列就是{1,3,4,5,6,7}或者{1,3,4,5,6,19}
方法1: 假设我们的初始的序列S1。那我们从小到大先排序一下。得到了S1'。这样我们再球 S1和S1'的最长公共子序列就可以知道答案了:)是不是有点巧妙啊
方法2 DP:
我们定义L(j)表示以第j个元素结尾的最长递增字串长度,是一个优化的子结构,也就是最长递增子序列.那么L(j)和L(1..j-1)的关系可以描述成
L(j) = max {L(i), i
//最长递增子序列(Longest Increase Subsequence)
#include <vector>
#include <iostream>
template <typename T>
T max(T const & a, T const & b)

{
return a>b?a:b;
}
//L(j) = max {L(i), i
//return the max LIS length
//output pos: start position of the LIS
int lis(int n, int const data[])

{
std::vector <int> L(n);
int maxLen = 0;
L[0] = 1;
for(int j=1; j<n; j++)
{
L[j]=1;
for(int i=0; i<j; i++)
{
if(data[i]<data[j])
L[j] = max(L[j], L[i]+1);
}
maxLen = max(maxLen, L[j]);
std::cout << j << " " << maxLen << std::endl;
}
return maxLen;
}

void main()

{
std::vector<int> data;
std::cout<<"Input data:\n";
int a;
while(std::cin>>a)
data.push_back(a);
int maxN = lis(data.size(), &data[0]);
std::cout<<maxN;
}