1. 程式人生 > >動態規劃 最長上升子序列(LIS)

動態規劃 最長上升子序列(LIS)

O(N2)寫法:

memset(dp, 0, sizeof(dp))

for(i = 0; i < n; i++) {

         dp[i]= 1;

         for(j= 0; j < i; j++) {

                   if(s[j]< s[i]) dp[i] = max(dp[i], dp[j] + 1);

         }

}

O(nlogn)寫法1:( dp[i]存長度為i + 1的上升子序列中末尾元素的最小值)

fill(dp, dp + n, inf);

for(i = 0; i < n; i++) {

         *lower_bound(dp,dp + n, a[i]) = a[i];

}

printf(“%d\n”, lower_bound(dp, dp + n, inf)– dp);

O(nlogn)寫法2:dp[i]存長度為i的上升子序列中末尾元素的最小值,下標從1開始

         intk = 1;

         b[1]= a[1];

         for(i= 2; i <= n; i++) {

                   if(a[i]> b[k]) {

                            b[++k]= a[i];

                   }

                   else{

                            char*pos = lower_bound(b, b + k,a[i]);

                            *pos= a[i];

                   }

         }

         printf("%d\n",k);

幾個題目:

怎麼寫都可以過

兩道LIS裸題,nlogn 都可以過

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
int a[100100], b[100100];
int main() {
	int n;
	while(~scanf("%d", &n)) {
		int i, j;
		for(i = 0; i < n; i++) {
			scanf("%d", a + i);
		}
		int k = 0;
		b[0] = a[0];
		for(i = 1; i < n; i++) {
			if(a[i] > b[k]) {
				b[++k] = a[i];
			}
			else {
				*lower_bound(b, b + k, a[i]) = a[i];
			}
		}
		printf("%d\n", k + 1);
	}
	return 0;
}