Under construction

Still being built. Things may change

DFS Order

Time limit2sMemory limit2048 MB

Summary
Given the cost to add or remove each edge, find the minimum total cost so that vertices 1 to N form a valid DFS order starting from vertex 1.
Level

Medium7 of 10

Topics
Dynamic programming, DFS, Tree, Graph
Solved
No attempts yet

Statement

Bessie has a simple undirected graph with vertices labeled 11 to NN (2≤N≤7502 \le N \le 750). She generates a depth-first search (DFS) order of the graph by calling dfs(1) as defined in the code below. Each adjacency list adj[i] (1≤i≤N1 \le i \le N) may be permuted arbitrarily before the search starts, so one graph can have several possible DFS orders.

vector<bool> vis(N + 1);
vector<vector<int>> adj(N + 1);  // adjacency list
vector<int> dfs_order;

void dfs(int x) {
    if (vis[x]) return;
    vis[x] = true;
    dfs_order.push_back(x);
    for (int y : adj[x]) dfs(y);
}

For every pair of vertices (i,j)(i,j) with 1≤i<j≤N1 \le i < j \le N, you are given an integer ai,ja_{i,j} (0<∣ai,j∣≤10000 < |a_{i,j}| \le 1000).

  • If ai,j>0a_{i,j} > 0, edge (i,j)(i,j) is not in the graph and can be added for cost ai,ja_{i,j}.
  • If ai,j<0a_{i,j} < 0, edge (i,j)(i,j) is in the graph and can be removed for cost −ai,j-a_{i,j}.

Find the minimum total cost to change the graph so that [1,2,…,N][1, 2, \dots, N] is a possible DFS order.

Input

The first line contains NN. Then N−1N-1 lines follow. The (j−1)(j-1)th line contains a1,j,a2,j,…,aj−1,ja_{1,j}, a_{2,j}, \dots, a_{j-1,j}, separated by spaces.

Output

Print the minimum total cost to change the graph so that [1,2,…,N][1, 2, \dots, N] is a possible DFS order.

Examples3

  1. Example 1

    Input
    4
    1
    2 3
    40 6 11
    
    Expected output
    10
    
  2. Example 2

    Input
    5
    -1
    10 -2
    10 -7 10
    -6 -4 -5 10
    
    Expected output
    5
    
  3. Example 3

    Input
    4
    -1
    -2 300
    4 -5 6
    
    Expected output
    9