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.
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.
Print the number of steps, so that the line remains the same afterward.
10 10 9 7 8 6 5 3 4 2 1
2
6 1 2 3 4 5 6
0
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.
思路:考虑第i个人是被谁杀的。他可以被他前一个人杀,如果杀不了,则被杀掉前一个人的人所杀,类推,找到能杀掉第i个人的人,若都杀不死他,则记录不能杀死他。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
int n,ans,flag;
int a[100005],b[100005],xb[100005]; // a[]-存输入的数据
// b[]-存需要几次操作将他杀掉 xb[]-存杀掉第i个人的人的下标
void solve()
{
int i,j,ma;
ans=-1;
b[1]=xb[1]=0; // 默认b[1]杀不掉
for(i=2; i<=n; i++) //从第二个开始判断
{
ma=0;
flag=0; // 存a[i]是否能被杀掉
j=i-1;
while(a[j]<a[i]&&j)
{
if(!b[j]) // 如果a[j]不能被前面人杀掉 则a[i]也不能
{
flag=1;
break;
}
if(b[j]>ma) ma=b[j];
j=xb[j]; // 跳转到杀死a[j]的人
}
if(!flag) b[i]=ma+1; //如果被杀死 则需ma+1步
else b[i]=0; // 没被杀死则需要0步
xb[i]=j; // 记录是谁杀死他的
// printf("i:%d b[i]:%d xb[i]:%d\n",i,b[i],xb[i]);
}
for(i=1; i<=n; i++)
{
if(ans<b[i]) ans=b[i];
}
}
int main()
{
int i,j;
while(~scanf("%d",&n))
{
for(i=1; i<=n; i++)
{
scanf("%d",&a[i]);
}
solve();
printf("%d\n",ans);
}
return 0;
}