题目链接:http://hihocoder.com/problemset/problem/1620
解析:维护一棵树,树根里面存(没有找到第一个大于该值的)最小值的编号,一直维护就好了,借鉴大佬得100分的代码
代码:
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<queue>
using namespace std;
typedef long long LL;
int a[500009], t[500009];
int ans[100009];
void update(int x)
{
if(t[x<<1] == -1) t[x] = t[x<<1|1];
else if(t[x<<1|1] == -1) t[x] = t[x<<1];
else if(a[t[x<<1]] < a[t[x<<1|1]]) t[x] = t[x<<1];
else t[x] = t[x<<1|1];
if(x == 1) return ;
update(x>>1);
}
int main()
{
int n;
scanf("%d", &n);
for(int i = 1; i <= n; i++) scanf("%d", &a[i]);
memset(t, -1, sizeof(t));
memset(ans, -1, sizeof(ans));
for(int i = 1; i <= n; i++)
{
int p;
while((p=t[1]) != -1 && a[p] < a[i])
{
ans[p] = i - p;
t[p+n] = -1;
update((p+n)/2);
}
t[i+n] = i;
update((i+n)/2);
}
for(int i = 1; i <= n; i++) printf("%d\n", ans[i]);
return 0;
}