@Chilling
2017-02-16T17:57:42.000000Z
字数 2280
阅读 942
线段树
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), that ai > aj. The displeasure of the 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 — the number of walruses in the queue. The second line contains integers .
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" (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.
Example
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
题意:给出n个数字,每个数字下标为i,比它小的最右端的数字的下标为k,求k-i-1,若右边没有比它更小的数字,则为-1。
分析:对于每一个数字来说,先判断是否有比它小的数字,然后先找右边的区间,若没有再找左边的。每一个数字查询完之后,更新这个位置,让它变成无穷大,之后的查询就不会再找到左边的区间了!
#include<algorithm>
#include<stdio.h>
const int INF=0x3f3f3f3f;
using namespace std;
int a[100005];
int ans[100005];
struct node
{
int l,r,minx;
}s[100005*4];
void build(int id,int l,int r)
{
s[id].l=l;
s[id].r=r;
if(l==r)
s[id].minx=a[l];
else
{
int mid=(l+r)/2;
build(id*2,l,mid);
build(id*2+1,mid+1,r);
s[id].minx=min(s[id*2].minx,s[id*2+1].minx);
}
}
int query(int id,int l,int r,int i)
{
if(s[id].l==s[id].r)
return s[id].l-i-1;
int mid=(s[id].l+s[id].r)/2;
if(a[i]>s[id*2+1].minx)
query(id*2+1,mid+1,r,i);
else
query(id*2,l,mid,i);
}
int rep(int id,int i)
{
if(s[id].l==s[id].r)
s[id].minx=INF;
else
{
int mid=(s[id].l+s[id].r)/2;
if(i<=mid)
rep(id*2,i);
else
rep(id*2+1,i);
s[id].minx=min(s[id*2].minx,s[id*2+1].minx);
}
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
build(1,1,n);
for(int i=1;i<=n;i++)
{
if(s[1].minx>=a[i])
ans[i]=-1;
else
ans[i]=query(1,1,n,i);
rep(1,i);
}
printf("%d",ans[1]);
for(int i=2;i<=n;i++)
printf(" %d",ans[i]);
printf("\n");
}
return 0;
}