回顾经典问题算法:LIS, LCS-(DP类别)

时间:2023-03-08 21:42:02

LIS,最长递增子序列
说明见:http://blog.csdn.net/sdjzping/article/details/8759870

 #include <iostream>
#include <cstdlib> using namespace std; int LIS(int* arr, int len) {
if (arr == NULL || len < ) return ;
int LIS[len] = {};
int mlen = ;
for (int i=; i<len; i++) {
LIS[i] = ;
for (int j = ; j < i; j++) {
if (arr[j] < arr[i] && LIS[i] < LIS[j] + ) {
LIS[i] = LIS[j] + ;
}
}
if (LIS[i] > mlen) {
mlen = LIS[i];
}
}
return mlen;
} int main() {
int arr[] = {, -, , -, , -, , -};
int len = sizeof(arr) / sizeof(arr[]);
cout<<LIS(arr, len)<<endl;
system("pause");
return ;
}

再给出nlogn的解法,其中len2val数组就是记录当前LIS长度时结尾的数字(可能情况下的最小值,如1,3和1,2同样可以构成长度为2的LIS但是取len2val[2]=2),关于这个数组的详细说明,可以参考第一个给出的连接,相对于第一个算法的改进就是该数组是有序的,可以使用二分搜索,即在数组中找到第一个比待处理值V大或相等的index设为I(就是序列长度),那么这个V必然可以插入到以len2val[I-1]结尾的长度为I-1的序列后部,形成新序列的长度为I,因而更新数组len2val[I] = V(更新是因为当前值肯定是大于等于V的,因为一开始就是根据这个条件进行搜索的)。这个查找的过程可以用STL中的lower_bound来做,这里自己按照源码写了一个直接返回索引的版本,STL中返回的是迭代器(数组迭代器就是元素指针,比较时还需减掉数组起始位置,才能得到索引)。

 int idx_lower_bound(int a[], int begin, int end, int target) {
int count = end - begin;
int first = begin;
while (count > ) {
int step = count/;
int idx = first + step;
if (a[idx] < target) {
first = ++idx;
count = count - step - ;
} else {
count = step;
}
} return first;
} int LIS_NLOGN(int arr[], int len) {
if (arr == NULL || len < ) {
return ;
}
int* len2idx = new int[len+]; len2idx[] = arr[];
int maxlen = ;
for (int i=; i<len; i++) {
char ch = arr[i];
int upper = idx_lower_bound(len2idx, , maxlen + , ch);
len2idx[upper] = ch;
if (upper > maxlen) {
maxlen = upper;
}
}
return maxlen;
}

LCS,最长公共子序列

 #include <iostream>
#include <cstdlib>
#include <cstring> using namespace std; int max(int a, int b) {
return a > b ? a : b;
} int LCS(const char* s1, int len1, const char* s2, int len2) {
if (s1 == NULL || s2 == NULL || len1 < || len2 < ) return ; int dp[len1 + ][len2 + ]; for (int i=; i<=len1; i++) {
for (int j=; j<=len2; j++) {
dp[i][j] = ;
}
} for (int i=; i<= len1; i++) {
for (int j=; j<=len2; j++) {
if (s1[i-] == s2[j-]) {
dp[i][j] = dp[i-][j-] + ;
} else {
dp[i][j] = max(dp[i-][j], dp[i][j-]);
}
}
}
for (int i=; i<=len1; i++) {
for (int j=; j<=len2; j++) {
cout<<" "<<dp[i][j];
}
cout<<endl;
}
return dp[len1][len2];
}; int main() {
const char* s1 = "helloyyc";
const char* s2 = "xellxddc"; cout<<LCS(s1, strlen(s1), s2, strlen(s2))<<endl; system("pause");
return ;
}