zoukankan      html  css  js  c++  java
  • POJ2533——DP(LCS+LDS)——Longest Ordered Subsequence

    Description

    A numeric sequence of ai is ordered if a1 < a2 < ... < aN. Let the subsequence of the given numeric sequence (a1a2, ..., aN) be any sequence (ai1ai2, ..., aiK), where 1 <= i1 < i2 < ... < iK <= N. For example, sequence (1, 7, 3, 5, 9, 4, 8) has ordered subsequences, e. g., (1, 7), (3, 4, 8) and many others. All longest ordered subsequences are of length 4, e. g., (1, 3, 5, 8).

    Your program, when given the numeric sequence, must find the length of its longest ordered subsequence.

    Input

    The first line of input file contains the length of sequence N. The second line contains the elements of sequence - N integers in the range from 0 to 10000 each, separated by spaces. 1 <= N <= 1000

    Output

    Output file must contain a single integer - the length of the longest ordered subsequence of the given sequence.

    Sample Input

    7
    1 7 3 5 9 4 8

    Sample Output

    4
    

    Source

    Northeastern Europe 2002, Far-Eastern Subregion
    大意:没什么好说的~模板题,取最大就行
    #include<cstdio>
    #include<algorithm>
    #include<cstring>
    using namespace std;
    const int MAX = 11000;
    int a[MAX],b[MAX];
    int main()
    {
        int n;
        int l,r,mid;
        scanf("%d",&n);
        for(int i = 1; i <= n ;i++)
            scanf("%d",&a[i]);
            // LCS
        b[1] = a[1];
        int k,i;
        for(i = 2, k = 1; i <= n ;i++){
                if(a[i] > b[k]) b[++k] = a[i];
               else {
                l = 1; r = k;
                  while(l<=r){
                       mid = (l + r) >> 1;
                       if(b[mid] < a[i]) l = mid + 1;
                       else if(b[mid] > a[i]) r = mid - 1;
                       else break;
                  }
                  b[l] =a[i];
               }
        }
        int temp1 = k;
        // LDS
        memset(b,0,sizeof(b));
        b[1] = a[1];
        for(i = 2, k = 1; i <= n ;i++){
               if(a[i] < b[i]) b[++k] = a[i];
              else {
                  l = 1; r = k;
                 while(l <= r){
                  mid = (l + r) >> 1;
                 if(b[mid] > a[i]) l = mid + 1;
                 else if(b[mid] < a[i]) r = mid -1;
                 else break;
                 }
                 b[l] = a[i];
              }
        }
        int temp2 = k;
        printf("%d",max(temp1,temp2));
        return 0;
    }
    View Code
  • 相关阅读:
    轨迹预测-运动递归函数
    Mandelbrot集合及其渲染
    如何检测一个圆在多个圆内?
    【转】三十分钟掌握STL
    【转】如何理解c和c++的复杂类型声明
    有1,2,3一直到n的无序数组,排序
    归并排序
    希尔排序
    快速排序
    冒泡排序
  • 原文地址:https://www.cnblogs.com/zero-begin/p/4366079.html
Copyright © 2011-2022 走看看