1. 程式人生 > >CodeForces 91B(單點查詢)

CodeForces 91B(單點查詢)

題意:有海象排隊,每個海象都有不滿意度,取決於離他前面的最遠的年齡比他小的海象和他直接站的海象數,給出佇列裡每個海象的年齡,輸出每個海象的不滿意度,如果沒有不滿意輸出-1。
題解:線段樹查詢最遠的比自己年齡小的海象的下標。

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100050;
int n, a[N], tree[N << 2];

void pushup(int k) {
    tree[k] = min(tree[k * 2
], tree[k * 2 + 1]); } void build(int k, int left, int right) { if (left == right) { tree[k] = a[left]; return; } int mid = (left + right) / 2; build(k * 2, left, mid); build(k * 2 + 1, mid + 1, right); pushup(k); } int query(int k, int left, int right, int l1, int
r1, int x) { if (left == right) { if (tree[k] < x) return left; return -1; } int mid = (left + right) / 2; if (r1 > mid && tree[k * 2 + 1] < x) return query(k * 2 + 1, mid + 1, right, l1, r1, x); else if (l1 <= mid) return query(k * 2
, left, mid, l1, r1, x); return -1; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); build(1, 1, n); for (int i = 1; i < n; i++) { int temp = query(1, 1, n, i + 1, n, a[i]); if (temp == -1) printf("-1 "); else printf("%d ", temp - i - 1); } printf("-1\n"); return 0; }