Cod sursa(job #3241384)

Utilizator obsidianMidnight Majesty obsidian Data 29 august 2024 18:09:20
Problema Subsir crescator maximal Scor 30
Compilator java Status done
Runda Arhiva educationala Marime 2.22 kb
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.*;

public class Main {
    public static Scanner sc;
    public static PrintWriter pw;

    static {
        try {
            sc = new Scanner(new FileReader("scmax.in"));
            pw = new PrintWriter("scmax.out");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    static class FenwickTreeMax {
        private final int[] nodes;
        private final int n;

        public FenwickTreeMax(int n) {
            this.n = n;
            this.nodes = new int[n + 1];
            Arrays.fill(this.nodes, 0);
        }

        public int queryMax(int index) {
            int max = 0;
            while (index > 0) {
                max = Math.max(max, nodes[index]);
                index -= (index & (-index));
            }
            return max;
        }

        public void update(int index, int value) {
            while (index <= n) {
                nodes[index] = Math.max(nodes[index], value);
                index += (index & (-index));
            }
        }
    }

    public static void main(String[] args) {
        int n = sc.nextInt();
        int[] a = new int[n];
        int[] sorted = new int[n];
        for (int i = 0; i < n; ++i) {
            a[i] = sorted[i] = sc.nextInt();
        }
        Arrays.sort(sorted);
        // remove duplicates from sorted
        int cntUnique = 1;    // skip first
        for (int i = 1; i < n; ++i) {
            if (sorted[i] != sorted[cntUnique - 1]) {
                sorted[cntUnique] = sorted[i];
                ++cntUnique;
            }
        }

        int[] kThSorted = new int[n];
        for (int i = 0; i < n; ++i) {
            kThSorted[i] = Arrays.binarySearch(sorted, 0, cntUnique, a[i]) + 1;
        }

        FenwickTreeMax fenwickTree = new FenwickTreeMax(n);

        for (int i = 0; i < n; ++i) {
            int currBest = 1 + fenwickTree.queryMax(kThSorted[i]);
            fenwickTree.update(kThSorted[i], currBest);
        }

        int best = fenwickTree.queryMax(n);
        pw.println(best);
        pw.flush();
    }

}