https://cn.vjudge.net/problem/CodeForces-91B
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 n (2 ≤ n ≤ 105) — the number of walruses in the queue. The second line contains integers 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" (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
题意:给一个序列,从右边开始看,对于第i个数字a[i],在右边找到一个比它小(严格小)的,最靠右的位置,k,输出k-i-1,如果一个都找不到,输出-1。对于序列的每个元素都要输出。
思路:找最右边第一个比他小的数,如果序列是单调的那么可以二分查找,但是这个序列并不有序,我们可以构造一个单调序列,维护了一个严格单调递减的序列,然后二分就ok了
#include<bits/stdc++.h>
#pragma GCC optimize(3)
using namespace std;
typedef long long ll;
const int N=1e5+5;
struct node{
int x,id;
}s[N];
int a[N];
int top=0;
int two_find(int x){
int l=1,r=top,mid;
while(l<=r){
mid=(l+r)>>1;
if(s[mid].x>=x) l=mid+1;
else r=mid-1;
}
return l;
}
int main(){
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
s[++top]={a[n],n};
a[n]=-1;
for(int i=n-1;i>=1;i--){
int pos=two_find(a[i]);
if(pos>top){
if(a[i]<s[top].x) s[++top]=node{a[i],i};
a[i]=-1;
}
else{
if(a[i]<s[top].x) s[++top]=node{a[i],i};
a[i]=s[pos].id-i-1;
}
}
for(int i=1;i<=n;i++) printf("%d%c",a[i]," \n"[i==n]);
return 0;
}