zcmu1607: Cantilevered thorn strands of the second year (tree-like array)

Link: https://acm.zcmu.edu.cn/JudgeOnline/problem.php?id=1607

Topic

n number ai, q times query, ask how many numbers between 1 and x are larger than a[x]

Ideas

Discretization + tree array offline processing

Use unique discretization to know the relative size, and then you can use the tree array to record how many digits before the i-th bit are larger than him, record the ans array, and then directly access the ans array when inquiring

ac code

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define lowbit(x) x&(-x)
const int maxn = 1e5 + 500;
int a[maxn], b[maxn], ans[maxn], c[maxn];
void add(int x, int k){
    for(int i = x; i < maxn; i += lowbit(i))
        c[i] += k;
}
int get(int x){
    int ans = 0;
    for(int i = x; i > 0; i -= lowbit(i))
        ans += c[i];
    return ans;
}
int main(){
    int n, q;
    while(~scanf("%d",&n)){
        if(n == -1) break;
        memset(c, 0, sizeof(c));
        for(int i = 1; i <= n; i ++){
            scanf("%d",&a[i]);
            b[i] = a[i];
        }
        sort(b + 1, b + n + 1);
        int m = unique(b + 1, b + n + 1) - b;
        for(int i = 1; i <= n; i ++){
            int x = (n + 5) - (lower_bound(b + 1, b + m + 1, a[i]) - b); //保证所有数都大于0就成
            ans[i] = get(x);
            add(x, 1);
        }
        scanf("%d",&q);
        while(q --){
            int x; scanf("%d",&x);
            printf("%d\n",ans[x]);
        }
    }
    return 0;
}

 

Guess you like

Origin blog.csdn.net/weixin_43911947/article/details/112353375