Queue
链接
Description
There are n walruses standing in a queue in an airport. They are numbered starting from the queue’s tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai.
The i-th walrus becomes displeased if there’s a younger walrus standing in front of him, that is, if exists such j ( i < j ) j (i < j) j(i < j), that a i > a j a_i > a_j ai > aj. The displeasure of the i i i-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the i-th one. That is, the further that young walrus stands from him, the stronger the displeasure is.
The airport manager asked you to count for each of n walruses in the queue his displeasure.
Input
The first line contains an integer n ( 2 ≤ n ≤ 1 0 5 ) n (2 ≤ n ≤ 10^5) n(2 ≤ n ≤ 105) — the number of walruses in the queue. The second line contains integers a i ( 1 ≤ a i ≤ 1 0 9 ) a_i (1 ≤ a_i ≤ 10^9) ai(1 ≤ ai ≤ 109).
Note that some walruses can have the same age but for the displeasure to emerge the walrus that is closer to the head of the queue needs to be strictly younger than the other one.
Output
Print n numbers: if the i-th walrus is pleased with everything, print “ − 1 -1 −1” (without the quotes). Otherwise, print the i-th walrus’s displeasure: the number of other walruses that stand between him and the furthest from him younger walrus.
Examples
Input
6
10 8 5 3 50 45
Output
2 1 0 -1 0 -1
Input
7
10 4 6 3 2 8 15
Output
4 2 1 0 -1 -1 -1
Input
5
10 3 1 10 11
Output
1 0 -1 -1 -1
解析
这是一道线段树题目。(当然不止线段树一种做法)
我们通过线段树维护一个区间的最小值。
在查询使 a i > a j a_i>a_j ai>aj 成立的 j j j 时,优先在右子树查找,若右子树无法查询到有效结果,再在查找左子树进行查找。最后查询的结果中使 a i > a j a_i>a_j ai>aj 成立的 j j j 必然是最大的,则 j − i − 1 j-i-1 j−i−1 必然也是最大的。
代码
#include<cstdio>
#include<map>
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
int n,t[400001],a[100001],ans;
void build(int x,int l,int r)
{
if(l==r)
{
t[x]=a[l];
return;
}
int mid;
mid=(l+r)/2;
build(x*2,l,mid);
build(x*2+1,mid+1,r);
t[x]=min(t[x*2],t[x*2+1]);
}
int query(int x,int l,int r,int a,int b,int k)
{
if(a>r||b<l)
return -1;
if(t[x]>=k)
return -1;
if(l==r)
return l;
int pr,pl,m;
m=(l+r)/2;
//pl=query(x*2,l,m,a,b,k);
pr=query(x*2+1,m+1,r,a,b,k);
if(pr!=-1)//右子树优先
return pr;
else
return pl=query(x*2,l,m,a,b,k);
}
int main()
{
//freopen("test.in","r",stdin);
//freopen("test.out","w",stdout);
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
build(1,1,n);//线段树求区间最小值
for(int i=1;i<=n;i++)
{
ans=query(1,1,n,i+1,n,a[i]);
if(ans==-1)
printf("%d ",ans);
else
printf("%d ",ans-i-1);
}
return 0;
}