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 A 1,A 2,…,A N.
For each test case, output one integer indicating the maximum length of the deque.
3 7 1 2 3 4 5 6 7 5 4 3 2 1 5 5 5 4 1 2 3
7 5 3题意 : 给一个序列,要求按顺序从序列中取一个数,把这个数放进一个双端队列,即可以放在队头,或者队尾,也可以不放. 求最终在队列里的最长不下降序列的长度 :枚举每个位置,求以num[i]为起点的最长不下降子序列和以num[i]为结尾的最长不递增子序列。
并且把相同值的个数统计一下,最后要减去算重复了的。
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int MAXN = 100000 + 10; int n; int num[MAXN]; int stack1[MAXN]; int stack2[MAXN]; int dp1[MAXN]; int dp2[MAXN]; int same1[MAXN]; int same2[MAXN]; void DP( int *stack, int *dp, int *same ) //stack保存最长上身序列,dp[i],是以这个点开始的最长上身序列长度, { //same[i],以i点为最长上身子序列里有多少个重复的 ; int top = 0; //stack数组里的元素个数 stack[ ++top ] = num[0]; dp[0] = 1; same[0] = 1; int temp; for ( int i = 1; i < n; i++ ) { int x = upper_bound( stack + 1, stack + top + 1, num[i] ) - stack; //从stack数组中找比num[i]大的第一个数的下标 int y = lower_bound( stack + 1, stack + top + 1, num[i] ) - stack; //从stack数组中找比大于等于num[i]的第一个数的下标 if ( num[i] >= stack[top] ) //目前栈里有top个元素,如果比stack[top]大,就加入stack;符合上升序列 ; { stack[ ++top ] = num[i]; temp = top; //temp是目前stack的序列长度 } else { stack[x] = num[i]; //如果小于, 则更新stack里第一个比num[i]大的数; temp = x; } dp[i] = temp; same[i] = x - y + 1; //相同的重复个数 } return; } int main() { int T; scanf("%d", &T); while ( T-- ) { scanf( "%d", &n ); for ( int i = n - 1; i >= 0; --i ) scanf( "%d", &num[i] ); DP( stack1, dp1, same1 ); //枚举求最长上身序列 for ( int i = 0; i < n; ++i ) { // printf( "%d ", num[i] ); num[i] = -num[i]; //去负值 } //puts(""); DP( stack2, dp2, same2 );//求最长下降序列 int ans = 0; for ( int i = 0; i < n; ++i ) { //printf( "%d %d\n", dp1[i], dp2[i] ); //printf( "**%d %d\n", same1[i], same2[i] ); ans = max( ans, dp1[i] + dp2[i] - min( same1[i], same2[i] ) ); } printf( "%d\n", ans ); } return 0; }