题意: n n n个数,求出 a [ i ] a[i] a[i]后面最后一个小于 a [ i ] a[i] a[i]的数与 a [ i ] a[i] a[i]间的距离,如果没有小于 a [ i ] a[i] a[i]的数则输出 - 1 -1 -1
题解:从后往前遍历数组,单调队列维护一个递减的序列,每次判断将要插入的数与队尾的数的大小关系。
如果当前插入的数不能保持队列的单调性则二分求答案,如果能保持,就说明这个数小于队列里的最小值,直接输出-1
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <string>
using namespace std;
typedef long long ll;
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define mem(a,b) memset(a,b,sizeof(a))
#define lowbit(x) x&-x
const int maxn = 1e5 + 5;
const int mod = 1e9 + 7;
const double eps = 1e-6;
const double pi = acos(-1.0);
#define lowbit(x) x&-x
const int maxn = 1e5 + 5;
const int mod = 1e9 + 7;
const double eps = 1e-6;
const double pi = acos(-1.0);
int n,a[maxn],qmin[maxn],ans[maxn];
int main(){
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
while(~scanf("%d",&n)){
for(int i = 1; i <= n; i++)
scanf("%d",&a[i]);
int r1 = 0,f1 = 0;
for(int i = n; i >= 1; i--){
if(r1 == 0 || a[i] < a[qmin[r1-1]]) qmin[r1++] = i;
if(a[i] <= a[qmin[r1-1]]) ans[i] = -1;
else{
int l = 0,r = r1;
int res = 0;
while(l <= r){
int mid = (l+r)>>1;
if(a[qmin[mid]] < a[i]){
res = mid;
r = mid-1;
}else{
l = mid+1;
}
}
ans[i] = qmin[res]-1-i;
}
}
for(int i = 1; i <= n; i++)
printf("%d ",ans[i]);
printf("\n");
}
return 0;
}