N (1 <= n <= 100,000) monkeys in the mountains, conveniently numbered 1..N, is once again standing in a row. Monkey i has height hi (1 <= hi <= 1,000,000).
Each monkey are looking to he left toward those with higher index numbers. We say that monkey i ' looks up ' to monkey J if I < J and hi< Hj. For each monkey I, we would like to know the index of the first monkey on line looked up to by Monkey I.
Input
Input consists of several testcases. The format of each case as follow:
Line 1: A single integer:n
Lines 2..n+1:line i+1 contains the single Integer:hi
Output
For each testcase, output N lines. Line I contains a single integer representing the smallest index of a monkey up to which monkey I looks. If no such monkey exists, print 0.
Sample Input
6326112
Sample Output
330660
Hint
Monkey 1 and 2 both look up to Monkey 3; Monkey 4 and 5 both look up to monkey 6; and Monkey 3 and 6 does not look up to any monkey.
Test instructions: Tell n a row of monkeys, each monkey to the right, ask the first higher than the position of the monkey, no output 0, the last one is 0
#include <iostream> #include <stdio.h> #include <string> #include < cstring> #include <queue> #include <cmath> #include <algorithm> #include <stack> #define N 100009using namespace Std;int a[n];int main () {int N; while (~SCANF ("%d", &n)) {for (int i=1;i<=n;i++) {scanf ("%d", &a[i]); } int ans[n]; Memset (ans,0,sizeof ans); The ans[n]=n;//is initialized to N, but the actual value is 0 for (int i=n-1;i>=1;i--)//Find the right first position {int tt=i, which is smaller than a[i]; while (Tt<n&&a[i]>=a[tt+1]) tt=ans[tt+1]; Ans[i]=tt; } for (int i=1;i<n;i++) {if (ans[i]==n)//When it is the last monkey, it is not guaranteed to be higher than the current monkey if (A[i]<a[n]) printf ("%d\n", ans[i]+1); else cout<<0<<endl; else printf ("%d\n", ans[i]+1); } cout<<0<<endl; } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Monkeys look to the right, FOJ on a topic monotonous stack