dpの谁在我前面

来源:互联网 发布:盛势网络剧07bilibili 编辑:程序博客网 时间:2024/06/08 05:07

题目:

Description

There are N(1<=N<=50000)students stand in a queue.We assume that every can only see the students that are in front of him and taller than him

.

For example, there are 6 students standing in a queue with height of
4 3 1 2 5 2,begining from the front student. In this example, student 3's height is 1, and he can see 2 persons. Student 6, although many students in front are taller than him, but he can only see the student with height of 5.

Now, given the number of students in a queue, and the height of each, can you find the student that can see most persons.

Input

Input contains multiple test cases. The first line is a integer T, the number of cases.The first line of each case is a integer N, the number of students.The second line of each case contains the heights of students from front to back.

Output

For each test case, print a line with a integer M, representing the maximum number of students can someone can see.

Sample Input

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

Sample Output

2
0

思路:主要是找到每个人的first[i],这个是该学生i的前面的第一个比他高的人,这样就可以写状态迁移方程了see[i]=see[first[i]]+1;

一开始超时了,后来才发现原来是在找first[i]的那一步,稍微改了一下:j=first[j];因为之前有许多的first[i]已经找过了,如果j不满足那么直接再找first[j]就可以了,不用j--,一个接着一个找,这样会超时的!!!!注意!!!!

代码如下:


#include<iostream>#include<cstring>using namespace std;int h[50001];//每个人的高度int first[50001];//前面第一个比他高的人的位置int see[50001];//能看见的人数int main(){int t,n;int best;cin>>t;while(t--){cin>>n;memset(h,0,sizeof(h));memset(first,0,sizeof(first));memset(see,0,sizeof(see));for(int i=1;i<=n;i++)cin>>h[i];best=0;for(int i=1;i<=n;i++){int j;for(j=i-1;j>0&&h[j]<=h[i];j=first[j]);//这个点一定要注意first[i]=j;if(first[i]==0)see[i]=0;elsesee[i]=see[j]+1;if(see[i]>best)best=see[i];}cout<<best<<endl;}//system("pause");return 0;}




0 0
原创粉丝点击