AcWing 1265. 数星星 (树状数组)

Problem

树状数组新手表示看不出这是一道树状数组的应用题。
这个题需要累计左下角的星星数量,枚举会超时;纵坐标按照升序给出,对于新来的xy,y是当前纵坐标最大值,只需累计1到x的星星即可,然后树状数组优化。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter pw = new PrintWriter(System.out);
    static int n;
    static int a[], c[], level[];

    public static void main(String[] args) throws IOException {

        n = Integer.parseInt(br.readLine());
        a = new int[n + 1];
        c = new int[32010];
        level = new int[n + 1];
        for (int i = 0; i < n; i++) {
            String s[] = br.readLine().split(" ");
            int x = Integer.parseInt(s[0]) + 1;
            level[query(x)]++;
            add(x, 1);
        }

        for (int i = 0; i < n; i++) pw.println(level[i]);

        pw.flush();
        pw.close();
        br.close();
    }

    public static int lowbit(int x) {
        return x & -x;
    }

    public static void add(int u, int v) {
        for (int i = u; i <= 32009; i += lowbit(i)) c[i] += v; //范围0 <= x <= 32000
    }

    public static int query(int x) {
        int res = 0;
        for (int i = x; i > 0; i -= lowbit(i)) res += c[i];
        return res;
    }

}
发布了167 篇原创文章 · 获赞 3 · 访问量 3416

猜你喜欢

转载自blog.csdn.net/qq_43515011/article/details/104356403
今日推荐