Algorithm
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.
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.
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.
6
10 8 5 3 50 45
2 1 0 -1 0 -1
7
10 4 6 3 2 8 15
4 2 1 0 -1 -1 -1
5
10 3 1 10 11
1 0 -1 -1 -1
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
int main(){
long n; scanf("%ld", &n);
std::vector<std::pair<long, long> > a(n);
for(long p = 0; p < n; p++){scanf("%ld", &a[p].first); a[p].second = p;}
sort(a.begin(), a.end());
long mx(-1);
std::vector<long> f(n);
for(long p = 0; p < n; p++){
f[a[p].second] = (a[p].second > mx) ? (-1) : (mx - a[p].second - 1);
mx = (mx > a[p].second) ? mx : a[p].second;
}
for(long p = 0; p < n; p++){printf("%ld ", f[p]);}
puts("");
return 0;
}
Copy The Code &
Try With Live Editor
Input
10 8 5 3 50 45
Output
Demonstration
Codeforces Solution-B. Queue-Solution in C, C++, Java, Python