1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.util.*;

public class kug {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();
        TreeSet<Node>[] nodes = new TreeSet[n + 1];
        for (int i = 1; i <= n; ++i) {
            nodes[i] = new TreeSet<Node>();
        }
        for (int i = 1; i <= n; ++i) {
            for (int j = i; j <= n; ++j) {
                Node node = new Node(i, j, sc.nextInt());
                for (int k = i; k <= j; ++k) {
                    nodes[k].add(node);
                }
            }
        }

        long sum = 0, minSum = 0;
        HashSet<Node> existing = new HashSet();

        // Need to implement some smart DFS
        for (int i = 1; i <= n; ++i) {
            for (Node node : nodes[i]) {
                if (!existing.contains(node)) {
                    sum += node.cost;
                    existing.add(node);
                    break;
                }
            }
        }
        minSum = sum;
        sum = 0;
        existing.clear();

        for (int i = n; i >= 1; --i) {
            for (Node node : nodes[i]) {
                if (!existing.contains(node)) {
                    sum += node.cost;
                    existing.add(node);
                    break;
                }
            }
        }

        System.out.println(Math.min(sum, minSum));
    }
}

class Node implements Comparable {
    int from;
    int to;
    int cost;

    Node(int from, int to, int cost) {
        this.from = from;
        this.to = to;
        this.cost = cost;
    }

    @Override
    public int compareTo(Object o) {
        Node other = (Node) o;

        if (cost == other.cost) {
            if (from == other.from) {
                return to < other.to ? -1 : 1;
            }
            return from < other.from ? -1 : 1;
        }
        return cost < other.cost ? -1 : 1;
    }

    /*@Override
    public String toString() {
        return "Node{" +
                "from=" + from +
                ", to=" + to +
                ", cost=" + cost +
                '}';
    }*/
}