您的位置:首页 > 产品设计 > UI/UE

hdu 4604 Deque(DP递增递减序列,4级)

2013-07-24 11:55 357 查看

Deque

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 613 Accepted Submission(s): 180

[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
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.

[align=left]Output[/align]
For each test case, output one integer indicating the maximum length of the deque.

[align=left]Sample Input[/align]

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

[align=left]Sample Output[/align]

7 5 3

[align=left]Source[/align]
2013 Multi-University Training Contest 1

[align=left]Recommend[/align]
liuyiding

思路:从后往前求非递增,非递减,在记录相同元素的个数,结果就是 max(asc[i]+dsc[i]-same[i]);
求递增递减就不用说,如果没有相同元素的话很容易就知道结果了。那same怎么求呢?为啥这式子就对呢?
举个例子说,就10个元素的序列 2 2 2 2 1 1 2 2 2 3 结果就是10
要从后往前求,就先去个反 3 2 2 2 1 1 2 2 2 2
求非递减的最长序列是 2 2 2 2 2 2 2
非递增的最长序列是 3 2 2 2 2 2 2 2
然后去重就好了,但实际上这样的结果不是最优的,因为 1 1 是可以插入进来的,这个很奇妙的一幕就发生了,我们用二分优化这个求序列DP时
刚好就可以把序列1 1 插进来了变成1 1 2 2 2 2 2 这样去除重复元素就正确了。
题解就TMD的两三句话,智商捉鸡理解了老半天,大神们都不为我们小菜们思考下,解释下same。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int mm=1e5+9;
const int oo=1e9;
int cas,n;
int f[mm],asc[mm],dsc[mm],same[mm];
void get(int*f,int*sc,int*sam)
{
vector<int>q;
int a,b;
for(int i=0;i<n;++i)
{
a=lower_bound(q.begin(),q.end(),f[i])-q.begin();
b=upper_bound(q.begin(),q.end(),f[i])-q.begin();
if(b==q.size())q.push_back(f[i]);
else q[b]=f[i];
sc[i]=b+1;
sam[i]=min(sam[i],b-a+1);
}
}
int main()
{
while(~scanf("%d",&cas))
{
while(cas--)
{
scanf("%d",&n);
for(int i=0;i<n;++i)
scanf("%d",&f[i]);
reverse(f,f+n);///取反求递增递减,和原序求刚好相反,但不影响答案
memset(same,0x3f,sizeof(same));
//printf("%d\n",same[3]);
get(f,asc,same);
for(int i=0;i<n;++i)///取负再求递增,就是原先的递减
f[i]=-f[i];
get(f,dsc,same);
int ans=-oo;
for(int i=0;i<n;++i)
ans=max(ans,asc[i]+dsc[i]-same[i]);
printf("%d\n",ans);
}
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: