2015
09-17

# Deque

Today, the teacher gave Alice extra homework for the girl weren’t attentive in his class. It’s hard, and Alice is going to turn to you for help.
The teacher gave Alice a sequence of number(named A) and a deque. The sequence exactly contains N integers. A deque is such a queue, that one is able to push or pop the element at its front end or rear end. Alice was asked to take out the elements from the sequence in order(from A_1 to A_N), and decide to push it to the front or rear of the deque, or drop it directly. At any moment, Alice is allowed to pop the elements on the both ends of the deque. The only limit is, that the elements in the deque should be non-decreasing.
Alice’s task is to find a way to push as many elements as possible into the deque. You, the greatest programmer, are required to reclaim the little girl from despair.

The first line is an integer T(1≤T≤10) indicating the number of test cases.
For each case, the first line is the length of sequence N(1≤N≤100000).
The following line contains N integers A1,A2,…,AN.

The first line is an integer T(1≤T≤10) indicating the number of test cases.
For each case, the first line is the length of sequence N(1≤N≤100000).
The following line contains N integers A1,A2,…,AN.

3
7
1 2 3 4 5 6 7
5
4 3 2 1 5
5
5 4 1 2 3

7
5
3

pos1 > pos2时一样可证

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <map>
#include <queue>
#include <set>
#include <vector>
#define MAXM 111111
#define MAXN 111111
#define INF 1000000007
#define eps 1e-8
using namespace std;
typedef vector<int>::iterator Viter;
int n;
vector<int>g;
int a[MAXN];
int dp1[MAXN], dp2[MAXN], num1[MAXN], num2[MAXN];
void gao(int dp[], int num[])
{
g.clear();
Viter it;
for(int i = n – 1; i >= 0; i–)
{
int sz = g.size();
if(!sz || a[i] >= g[sz - 1])
{
g.push_back(a[i]);
dp[i] = sz + 1;
}
else
{
it = upper_bound(g.begin(), g.end(), a[i]);
dp[i] = it – g.begin() + 1;
*it = a[i];
}
pair<Viter, Viter>bounds = equal_range(g.begin(), g.end(), a[i]);
num[i] = bounds.second – bounds.first;
}
}
int main()
{
int T;
scanf("%d", &T);
while(T–)
{
scanf("%d", &n);
for(int i = 0; i < n; i++) scanf("%d", &a[i]);
gao(dp1, num1);
for(int i = 0; i < n; i++) a[i] = -a[i];
gao(dp2, num2);
int ans = 0;
for(int i = 0; i < n; i++)
ans = max(ans, dp1[i] + dp2[i] – min(num1[i], num2[i]));
printf("%d\n", ans);
}
return 0;
}