Cod sursa(job #3241301)

Utilizator obsidianMidnight Majesty obsidian Data 28 august 2024 18:43:00
Problema Subsir crescator maximal Scor 40
Compilator java Status done
Runda Arhiva educationala Marime 2.62 kb
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
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;
            int max_idx = -1;
            while (index > 0) {
                if (max_idx == -1 || max < nodes[index]) {
                    max = nodes[index];
                    max_idx = index;
                }
                index -= (index & (-index));
            }
            return new int[]{max, max_idx};
        }

        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);

        int idx = 1;
        Map<Integer, Integer> sortedLeftmostIdx = new HashMap<>();
        sortedLeftmostIdx.put(sorted[0], idx);
        for (int i = 1; i < n; ++i) {
            sortedLeftmostIdx.putIfAbsent(sorted[i], ++idx);
        }

        FenwickTreeMax fenwickTree = new FenwickTreeMax(n);

        for (int i = 0; i < n; ++i) {
            Integer sortedIdx = sortedLeftmostIdx.get(a[i]);
            int currBest = 1 + fenwickTree.queryMax(sortedIdx - 1)[0];
            fenwickTree.update(sortedIdx, currBest);
        }

        int[] best = fenwickTree.queryMax(n);

        int maxCnt = best[0];

       pw.println(maxCnt);

        List<Integer> solution = new ArrayList<>();
        for (int i = best[1]; i >= 1; ) {
            solution.add(sorted[i - 1]);
            best = fenwickTree.queryMax(i - 1);
            i = best[1];
        }
        for (int i = maxCnt - 1; i >= 0; --i) {
            pw.print(solution.get(i) + " ");
        }
        pw.flush();
    }
}