1. 程式人生 > >91B——Queue (單調佇列之海象比年齡)

91B——Queue (單調佇列之海象比年齡)

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 
題意:       在機場的某佇列中,站著 n 只海象。它們從佇列的尾部開始編號:第 1 只海象站在隊尾,第 n 只海象表示站在隊首。第 i 只海象的年齡等於 ai 。第 i 只海象在以下情況下會變得不愉快:如果有更年輕的海象站在它的前面,即存在這樣的 j (i < j),使得 ai > aj 。第 i 只海象的 不愉快 指數,等於第 i 只海象與在它前面最遠的更年輕海象之間,所存在的海象數目。換言之,更年輕的海象站在它前方越遠,不愉快指數越強。對於佇列中 n 只海象中的每一隻,機場管理員請您求出它的不愉快指數。思路:

       從尾部開始遍歷,單調存遞減序列,二分查詢。

#include<algorithm>
#include<string.h>
#include<stdio.h>
#define M 100010
using namespace std;
int a[M],tail,ans[M];
struct node
{
    int x,i;
};
node q[M];
int erfen(int x)
{
    int l=0,r=tail,pan;
    while(r>=l)
    {
        pan=(r+l)/2;
        if(x>q[pan].x)
        {
            r=pan-1;
        }
        else
        {
            l=pan+1;
        }
    }
    return l;
}
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        tail=0;
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        for(int i=n;i>0;i--)
        {
            if(tail==0||q[tail-1].x>=a[i])
            {
                q[tail].x=a[i];
                q[tail++].i=i;
                ans[i]=-1;
            }
            else
            {
                int j=erfen(a[i]);
                ans[i]=q[j].i-i-1;
            }
        }
        for(int i=1;i<n;i++)
        {
            printf("%d ",ans[i]);
        }printf("%d\n",ans[n]);
    }
}