#P11676. Minimum Cost for DFS Order

    ID: 13766 Type: Default 1000ms 256MiB

Minimum Cost for DFS Order

Minimum Cost for DFS Order

Bessie has an undirected simple graph with vertices numbered from 11 to NN (2N7502 \le N \le 750). The graph is represented by its adjacency lists. Initially, for every pair of vertices (i,j)(i,j) with 1i<jN1\le i<j\le N, a cost ai,ja_{i,j} is given (with 0<ai,j10000<|a_{i,j}|\le 1000), where:

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

Bessie calls the following DFS routine starting from vertex 11:

[ \begin{array}{l} vis[1 \dots N] = false,\ \text{dfs_order} = [,],\ \text{function } dfs(x): \ \quad \textbf{if } vis[x] \textbf{ then return}.\ \quad vis[x] = true,\ \quad dfs_order.push(x),\ \quad \textbf{for each } y \textbf{ in } adj[x] \textbf{ do } dfs(y).\ \end{array} ]

Before the DFS starts, Bessie can rearrange each adjacency list arbitrarily. Therefore, a single graph might yield multiple DFS orders.

The goal is to modify the graph with minimum total cost so that the sequence [1,2,,N][1,2,\dots,N] becomes a valid DFS order.

Observation: In order for [1,2,,N][1,2,\dots,N] to be a DFS order, there must be a DFS tree with the following chain of tree edges: (1,2)(1,2), (2,3)(2,3), ..., (N1,N)(N-1,N). With the freedom to choose the order in each adjacency list, it is sufficient to ensure that for each ii from 11 to N1N-1, the edge (i,i+1)(i,i+1) exists in the final graph. Any extra edge can be placed later in the adjacency order without affecting the DFS order.

Thus, for every i=1,2,,N1i=1,2,\dots, N-1, if the edge (i,i+1)(i,i+1) is absent initially (i.e. ai,i+1>0a_{i,i+1}>0), you must add it at a cost of ai,i+1a_{i,i+1}. If ai,i+1<0a_{i,i+1}<0, the edge is already present and no cost is incurred.

Compute the minimum total cost required so that [1,2,,N][1,2,\dots,N] is a valid DFS order.

inputFormat

The first line contains an integer NN (2N7502 \leq N \leq 750). This is followed by N(N1)2\frac{N(N-1)}{2} integers representing ai,ja_{i,j} for every pair (i,j)(i,j) with 1i<jN1 \le i < j \le N. The integers for each ii are given in order for j=i+1,i+2,,Nj=i+1, i+2, \dots, N, separated by spaces or newlines.

outputFormat

Output a single integer: the minimum total cost to modify the graph so that [1,2,,N][1,2,\dots,N] is a valid DFS order.

sample

2
5
5

</p>