QMAX2 - Giá trị lớn nhất ver2
Tác giả: ladpro98
Ngôn ngữ: Java
import java.io.*;
import java.util.StringTokenizer;
public class Main {
public static void main(String args[]) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver object = new Solver();
object.solve(in, out);
out.close();
}
static class Solver {
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int a[] = new int[n + 1];
SegmentTree T = new SegmentTree(a);
for (int i = 1; i <= m; ++i) {
int type = in.nextInt();
int x = in.nextInt();
int y = in.nextInt();
if (type == 0) {
int value = in.nextInt();
T.increase(x, y, value);
} else {
out.println(T.getMaxValue(x, y));
}
}
}
}
static class SegmentTree {
Node root;
SegmentTree(int a[]) {
root = build(a, 1, a.length - 1);
}
void increase(int i, int j, int value) {
root.increase(i, j, value);
}
int getMaxValue(int i, int j) {
return root.getMaxValue(i, j);
}
class Node {
int l, r;
int lazy;
int maxValue;
Node left, right;
Node(int l, int r) {
this.l = l;
this.r = r;
this.lazy = 0;
this.maxValue = 0;
this.left = null;
this.right = null;
}
void gather() {
maxValue = Math.max(left.maxValue, right.maxValue);
}
void pushDown() {
if (lazy != 0) {
maxValue += lazy;
if (l != r) {
left.lazy += lazy;
right.lazy += lazy;
}
lazy = 0;
}
}
int getMaxValue(int i, int j) {
pushDown();
if (r < i || j < l) return 0;
if (i <= l && r <= j) return maxValue;
return Math.max(left.getMaxValue(i, j), right.getMaxValue(i, j));
}
void increase(int i, int j, int value) {
pushDown();
if (r < i || j < l) return;
if (i <= l && r <= j) {
lazy += value;
pushDown();
return;
}
left.increase(i, j, value);
right.increase(i, j, value);
gather();
}
}
Node build(int a[], int l, int r) {
Node cur = new Node(l, r);
if (l == r) {
cur.maxValue = a[l];
return cur;
}
int mid = l + r >> 1;
cur.left = build(a, l, mid);
cur.right = build(a, mid + 1, r);
cur.gather();
return cur;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}