AcWing 1270. 数列区间最大值 (线段树)

Problem

线段树模板题,线段树能解决的范围远多于树状数组,这个题的要求是求区间最大值。

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 = 100010, n, m;
    static int w[] = new int[N];
    static Node node[] = new Node[N * 4];

    public static void main(String[] rags) throws IOException {
        String s[] = br.readLine().split(" ");
        n = Integer.parseInt(s[0]);
        m = Integer.parseInt(s[1]);
        s = br.readLine().split(" ");
        for (int i = 1; i <= n; i++) w[i] = Integer.parseInt(s[i - 1]);

        build(1, 1, n);
        while (m-- > 0) {
            s = br.readLine().split(" ");
            int a = Integer.parseInt(s[0]);
            int b = Integer.parseInt(s[1]);
            pw.println(query(1, a, b));
        }

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

    private static void build(int u, int l, int r) {
        if (l == r) node[u] = new Node(l, r, w[r]);
        else {
            node[u] = new Node(l, r);
            int mid = l + r >> 1;
            build(u << 1, l, mid);
            build(u << 1 | 1, mid + 1, r);
            node[u].setMax(Math.max(node[u << 1].getMax(), node[u << 1 | 1].getMax()));
        }
    }

    public static int query(int u, int l, int r) {
        if (node[u].getL() >= l && node[u].getR() <= r) return node[u].getMax();

        int mid = node[u].getL() + node[u].getR() >> 1;
        int maxv = Integer.MIN_VALUE;
        if (l <= mid) maxv = query(u << 1, l, r);
        if (r > mid) maxv = Math.max(maxv, query(u << 1 | 1, l, r));
        return maxv;
    }


}

class Node {
    int l, r, max;

    public Node(int l, int r, int max) {
        this.l = l;
        this.r = r;
        this.max = max;
    }

    public Node(int l, int r) {
        this.l = l;
        this.r = r;
    }

    public int getL() {
        return l;
    }

    public void setL(int l) {
        this.l = l;
    }

    public int getR() {
        return r;
    }

    public void setR(int r) {
        this.r = r;
    }

    public int getMax() {
        return max;
    }

    public void setMax(int max) {
        this.max = max;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值