转载自:http://www.cnblogs.com/zhangchaoyang/articles/2012070.html
最大子序列
最大子序列是要找出由数组成的一维数组中和最大的连续子序列。比如{5,-3,4,2}的最大子序列就是 {5,-3,4,2},它的和是8,达到最大;而 {5,-6,4,2}的最大子序列是{4,2},它的和是6。你已经看出来了,找最大子序列的方法很简单,只要前i项的和还没有小于0那么子序列就一直向后扩展,否则丢弃之前的子序列开始新的子序列,同时我们要记下各个子序列的和,最后找到和最大的子序列。
代码如下:
复制代码
include
include
using namespace std;
int maxSubSum(const vector & arr,int &begin,int &end){
int maxSum=0;
int currSum=0;
int newbegin=0;
for(int i=0;i
include
include
include
using namespace std;
int main(){
const int len=14;
int arr[len]={1,9,3,8,11,4,5,6,4,1,9,7,1,7};
vector vec(&arr[0],&arr[len]);
vector<int> monoseqlen(len,1);
vector<int> preindex(len,-1);
int maxmonoseqlen=-1;
int maxmonoindex=-1;
for(int i=1;i<len;++i){
int curr=vec[i];
for(int j=0;j<i;++j){
if(vec[j]<vec[i]){
int msl=monoseqlen[j]+1;
if(msl>monoseqlen[i]){
monoseqlen[i]=msl;
preindex[i]=j;
}
}
}
}
for(int i=0;i<len;++i){
if(monoseqlen[i]>maxmonoseqlen){
maxmonoseqlen=monoseqlen[i];
maxmonoindex=i;
}
}
stack<int> st;
while(maxmonoindex>=0){
st.push(vec[maxmonoindex]);
maxmonoindex=preindex[maxmonoindex];
}
vector<int> rect;
while(!st.empty()){
rect.push_back(st.top());
st.pop();
}
vector<int>::iterator itr=rect.begin();
while(itr!=rect.end()){
cout<<*itr++<<"\t";
}
cout<<endl;
return 0;
}
最长公共子串(LCS)
找两个字符串的最长公共子串,这个子串要求在原字符串中是连续的。其实这又是一个序贯决策问题,可以用动态规划来求解。我们采用一个二维矩阵来记录中间的结果。这个二维矩阵怎么构造呢?直接举个例子吧:”bab”和”caba”(当然我们现在一眼就可以看出来最长公共子串是”ba”或”ab”)
b a b
c 0 0 0
a 0 1 0
b 1 0 1
a 0 1 0
我们看矩阵的斜对角线最长的那个就能找出最长公共子串。
不过在二维矩阵上找最长的由1组成的斜对角线也是件麻烦费时的事,下面改进:当要在矩阵是填1时让它等于其左上角元素加1。
b a b
c 0 0 0
a 0 1 0
b 1 0 2
a 0 2 0
这样矩阵中的最大元素就是 最长公共子串的长度。
在构造这个二维矩阵的过程中由于得出矩阵的某一行后其上一行就没用了,所以实际上在程序中可以用一维数组来代替这个矩阵。
代码如下:
include
include
include
using namespace std;
//str1为横向,str2这纵向
const string LCS(const string& str1,const string& str2){
int xlen=str1.size(); //横向长度
vector tmp(xlen); //保存矩阵的上一行
vector arr(tmp); //当前行
int ylen=str2.size(); //纵向长度
int maxele=0; //矩阵元素中的最大值
int pos=0; //矩阵元素最大值出现在第几列
for(int i=0;i
include
include
include
include
define LEFTUP 0
define LEFT 1
define UP 2
using namespace std;
int Max(int a,int b,int c,int *max){ //找最大者时a的优先级别最高,c的最低.最大值保存在*max中
int res=0; //res记录来自于哪个单元格
*max=a;
if(b>*max){
*max=b;
res=1;
}
if(c>*max){
*max=c;
res=2;
}
return res;
}
//调用此函数时请注意把较长的字符串赋给str1,这主要是为了在回溯最长子序列时节省时间。如果没有把较长的字符串赋给str1不影响程序的正确执行。
string LCS(const string &str1,const string &str2){
int xlen=str1.size(); //横向长度
int ylen=str2.size(); //纵向长度
if(xlen==0||ylen==0) //str1和str2中只要有一个为空,则返回空
return “”;
pair