2019icpc徐州网络赛 E.XKC's basketball team(线段树)
大意:给你长度n的数组和k,让你输出n个数,表示每个位置向右最远的位置pos,使得a[pos]-a[i]>=k,输出两个位置中间隔的数量。
思路:直接建一个维护区间最大值的线段树,每次查询直接查[i+1,n]范围内>=a[i]+k的最远位置即可。
我们查询的时候先查右儿子,没查到就查左儿子,否则答案必然在右儿子中,右儿子中没答案的话,那么答案必然在左儿子中(查询的区间要合法)
#include<bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define LL long long
#define SZ(X) X.size()
#define pii pair<int,int>
#define ALL(X) X.begin(),X.end()
using namespace std;
LL gcd(LL a, LL b) {return b ? gcd(b, a % b) : a;}
LL lcm(LL a, LL b) {return a / gcd(a, b) * b;}
LL powmod(LL a, LL b, LL MOD) {LL ans = 1; while (b) {if (b % 2)ans = ans * a % MOD; a = a * a % MOD; b /= 2;} return ans;}
const int N = 5e5 + 11;
int n;
LL m;
LL a[N];
#define mid (l+r>>1)
#define ls o<<1
#define rs o<<1|1
int t[N << 2];
void build(int o, int l, int r) {
if (l == r) {
t[o] = a[l];
return ;
}
build(ls, l, mid);
build(rs, mid + 1, r);
t[o] = max(t[ls], t[rs]);
}
int get(int o, int l, int r, int x, int y, int d) {
if (l == r && t[o] >= d) {
return l;
}
if (l == r)return -1;
int tmp = -1;
if (t[rs] >= d && y > mid) {
tmp = get(rs, mid + 1, r, x, y, d);
}
if (t[ls] >= d && x <= mid && tmp == -1) {
tmp = get(ls, l, mid, x, y, d);
}
return tmp;
}
int main() {
ios::sync_with_stdio(false);
cin >> n >> m;
for (int i = 1; i <= n; i++)cin >> a[i];
build(1, 1, n);
for (int i = 1; i <= n; i++) {
int tmp;
if (i == n)tmp = -1;
else tmp = get(1, 1, n, i + 1, n, a[i] + m);
if (tmp == -1)cout << -1;
else cout << tmp - i - 1;
if (i != n)cout << ' ';
else cout << '\n';
}
return 0;
}