2016年8月27日星期六

Longest Bitonic Subsequence

Problem
    Longest Bitonic Subsequence


Examples:
Input arr[] = {1, 11, 2, 10, 4, 5, 2, 1};
Output: 6 (A Longest Bitonic Subsequence of length 6 is 1, 2, 10, 4, 2, 1)

Input arr[] = {12, 11, 40, 5, 3, 1}
Output: 5 (A Longest Bitonic Subsequence of length 5 is 12, 11, 5, 3, 1)

Input arr[] = {80, 60, 30, 40, 20, 10}
Output: 5 (A Longest Bitonic Subsequence of length 5 is 80, 60, 30, 20, 10)

Solution
    max(lis[i] + rds[i] - 1) 1 <= i <= n

#include <iostream>
#include <cstring>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <map>
#include <vector>
using namespace std;

const int N = 1000010;
int a[N];
int lis[N];
int rds[N];
int n;
int main() {
    scanf("%d",&n);
    for (int i = 0; i < n; i ++) {
        scanf("%d",&a[i]);
    }
    memset(lis,0,sizeof(lis));
    memset(rds,0,sizeof(rds));
    lis[0] = 1;
    for (int i = 1; i < n; i ++) {
        lis[i] = 1;
        for (int j = 0; j < i; j ++) {
            if (a[i] > a[j] && lis[i] < lis[j] + 1) {
                lis[i] = lis[j] + 1;
            }
        }
    }
    rds[n - 1] = 1;
    for (int i = n - 2; i >= 0; i --) {
        rds[i] = 1;
        for (int j = i + 1; j < n; j ++) {
            if (a[i] > a[j] && rds[i] < rds[j] + 1) {
                rds[i] = rds[j] + 1;
            }
        }
    }
    int maxs = 0;
    for (int i = 0; i < n; i ++) {
        maxs = max(maxs,lis[i] + rds[i] - 1);
    }
    cout << maxs << endl;
}


Tips
   lis[i] >= 1 && rds[i] >= 1 where i between 1 and n

没有评论:

发表评论