Description
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.
You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.
Input
The first line of input contains integer n denoting the number of psychos, (1 ≤ n ≤ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive — ids of the psychos in the line from left to right.
Output
Print the number of steps, so that the line remains the same afterward.
Sample Input
10 10 9 7 8 6 5 3 4 2 1
2
6 1 2 3 4 5 6
0
Hint
In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] → [10 8 4] → [10]. So, there are two steps.
/**
题意:给出1到n的一个序列a[1].a[2]...a[n],
每一轮,如果a[i]>a[i+1],则称a[i]杀掉s[i+1],则可以从数列中去掉a[i+1],
并且,一个数可以同时将右边一个数杀掉并且被左边数杀掉,
问:最少经过几轮,不会存在杀掉关系?
分析:维护一个单调栈,反向加入初始序列,ans[i]表示数字i杀掉右边的可杀数需要的步数,
我们取最大的ans[i]就是答案。将i加入栈时,有以下情况:
1. i比栈顶元素a小,ans[i]=0;
2. i比栈顶元素a大,ans[i] = max( 1, ans[a]),(至少要为1,应该很好想),a出栈。
while(此时栈未空并且栈顶元素b仍然小),
则i可以杀掉他,在第max(ans[i]+1,ans[b])轮,b出栈。
i入栈。
最终栈中的序列即为最终序列,不存在杀掉关系。
*/
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<set>
using namespace std;
const int N = 100001;
int ans[N],q[N],d[N];
int top;
int main()
{
int i,j,k,m,n;
while(scanf("%d",&n)==1)
{
for(i=n; i>=1; i--) scanf("%d",d+i);
top = 0;
ans[d[1]] = 0;
int mx = 0;
q[++top] = d[1];
for(i=2; i<=n; i++)
{
if(d[i]<q[top])
q[++top] = d[i], ans[d[i]]=0;
else
{
int a = max(1,ans[q[top]]);
top--;
while(top && q[top]<d[i])
{
a= max(a+1,ans[q[top]]);
top--;
}
ans[d[i]] = a;
q[++top] = d[i];
mx = max(mx,ans[d[i]]);
}
}
printf("%d\n",mx);
}
return 0;
}