标签:
时间复杂度为 n*logn的LIS算法是用一个stack维护一个最长递增子序列
1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 #include <algorithm> 5 #include <iostream> 6 #include <queue> 7 #include <stack> 8 #include <vector> 9 #include <map> 10 #include <set> 11 #include <string> 12 using namespace std; 13 typedef long long LL; 14 const int INF = 1<<30; 15 const int N = 10000 + 10; 16 int min(const int &a, const int &b) 17 { 18 return a < b ? a :b; 19 } 20 int max(const int &a, const int &b) 21 { 22 return a < b ? b : a; 23 } 24 int st[N]; 25 int top; 26 void LIS(int *a, int n, int *dp) 27 { 28 int i,j; 29 top = 0; 30 st[top] = a[0]; 31 for(i=1; i<n; ++i) 32 { 33 if(a[i] > st[top]) 34 { 35 st[++top] = a[i]; 36 dp[i] = top +1 ; 37 } 38 else 39 { 40 int low = 0, high = top; 41 while(low <= high) 42 { 43 int mid = (low + high) >> 1; 44 if(st[mid]<a[i]) 45 low = mid + 1; 46 else 47 high = mid - 1; 48 } 49 st[low] = a[i]; 50 dp[i] = low +1; 51 } 52 } 53 } 54 int a[N]; 55 int dp[2][N]; 56 int main() 57 { 58 int n,i,j; 59 while(scanf("%d",&n)!=EOF) 60 { 61 for(i=0; i<n; ++i) 62 { 63 scanf("%d",&a[i]); 64 dp[0][i] = dp[1][i] = 1; 65 } 66 LIS(a,n,dp[0]); 67 68 int low = 0,high = n - 1; 69 while(low < high) 70 { 71 int t = a[low]; 72 a[low] = a[high]; 73 a[high] = t; 74 low ++; 75 high --; 76 } 77 LIS(a,n,dp[1]); 78 79 int ans = 0; 80 for(i=0; i<n; ++i) 81 { 82 int t = 2 * min(dp[0][i]-1,dp[1][n-i-1]-1) +1;//因为第二次dp是将数组倒过来dp,所以要n-i-1 83 ans = max(ans,t); 84 } 85 printf("%d\n",ans); 86 } 87 return 0; 88 }
标签:
原文地址:http://www.cnblogs.com/justPassBy/p/4435767.html