Cod sursa(job #1560112)

Utilizator AetheryonStefan Bereghici Aetheryon Data 1 ianuarie 2016 19:46:57
Problema Arbori de intervale Scor 0
Compilator java Status done
Runda Arhiva educationala Marime 2.24 kb
package euclid2;
import java.io.*;
import java.util.*;

/**
 * Created by Aetheryon on 28.12.2015.
 */

public class Main{
    public static int n,q,leaf;
    public static String URL_INPUT = "arbint.in";
    public static String URL_OUTPUT = "arbint.out";
    
    public static void main(String[] args) throws IOException{
        Scanner in = new Scanner(new FileInputStream(URL_INPUT));
        PrintStream out = new PrintStream(URL_OUTPUT);
        n = in.nextInt();
        q = in.nextInt();
        // construct a segment tree
        SegmentTree tree = new SegmentTree();
        for (int i=1;i<=n;++i){
            leaf = in.nextInt();
            tree.updateSegment(1,1,n,i,i,leaf);
        }
        while(q>0) {
            int type, a, b;
            type = in.nextInt(); a = in.nextInt(); b = in.nextInt();
            switch (type) {
                case 0 : out.println(tree.getMax(1, 1, n, a, b));
                         break;
                case 1 : tree.updateSegment(1,1,n,a,a,b);
                         break;
            }
            --q;
        }
    }

    public static class SegmentTree {
        private int[] treeNode;
        private int TREE_SIZE = 4000013;

        // constructor
        SegmentTree() {
            treeNode = new int[TREE_SIZE];
        }

        protected void updateSegment(int node, int x, int y, int left, int right, int value) {
            if (x > right || y < left || x > y) return;
            if (x >= left && y <= right) {
                treeNode[node] = value;
                return;
            }
            int middle = x + (y - x) / 2;
            updateSegment(node * 2, x, middle, left, right, value);
            updateSegment(node * 2 + 1, middle + 1, y, left, right, value);
            treeNode[node] = Math.max(treeNode[node*2], treeNode[node*2+1]);
        }

        protected int getMax(int node, int x, int y, int left, int right) {
            if (x > right || y < left || x > y) return 0;
            if (x >= left && y <= right) return treeNode[node];
            int middle = x + (y - x) / 2;
            return Math.max(getMax(node * 2, x, middle, left, right), getMax(node * 2 + 1, middle + 1, y, left, right));
        }
    }
}