Topic links: https://nanti.jisuanke.com/t/41387
Thinking: We need to move forward to maintain an ascending sequence from the rear.
Because: We want wi + m <= wj, j to take the maximum, i.e. the farthest from the j i, wi each index requires a determination is not greater than w (i + 1), to complete the sequence of increments maintain.
Why can better understand the code inside to maintain an ascending sequence
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> #include <stack> #include <string> #include <map> #include <cmath> using namespace std; typedef long long LL; #define inf 1e9 #define rep(i,j,k) for(int i = (j); i <= (k); ++i) #define rep__(i,j,k) for(int i = (j); i < (k); ++i) #define per(i,j,k) for(int i = (j); i >= (k); --i) #define per__(i,j,k) for(int i = (j); i > (k); --i) const int N = (int)5e5 + 10; int arr[N]; int ans[N]; struct node{ int index; int w; void set(int x,int y){ index = x; w = y; } }que[N]; int main(){ int n,m; scanf("%d%d",&n,&m); rep(i,1, n-) Scanf ( " % D " , ARR + I); int L, R & lt, MID, A; int len = 0 ; // last process to que [++ len]. SET (n-, ARR [n-]) ; ANS [n-] = - . 1 ; // per (I, N- . 1 , . 1 ) { // than before are large IF (ARR [I] + m> que [len] .W) { ANS [I] = - . 1 ; IF (ARR [I]> que [len] .W) que [ ++ len]. SET (I, ARR [I]); } //Smaller than the first one the else IF (ARR [I] + m <= que [ . 1 ] .W) { ANS [I] = que [ . 1 ] .index - I - . 1 ; // the printf ( "% D IS the this ANS IS% D Test \ n-", I, ANS [I]); } // in the middle answer the else { L = . 1 ; R & lt = len; the while (L <= R & lt) { mID = (L + R & lt)> > . 1 ; IF (ARR [I] + m <= que [MID] .W) { A = que [MID] .index; r = mid - 1; } else l = mid + 1; } // printf("arr[%d] = index %d - index %d - 1\n",i,A,i); ans[i] = A - i -1; } } // rep(i,1,ll) printf("%d ",que[i].index); // printf("\n"); printf("%d",ans[1]); rep(i,2,n) printf(" %d",ans[i]); printf("\n"); getchar(); getchar(); return 0; }