#P11676. Minimum Cost for DFS Order
Minimum Cost for DFS Order
Minimum Cost for DFS Order
Bessie has an undirected simple graph with vertices numbered from to (). The graph is represented by its adjacency lists. Initially, for every pair of vertices with , a cost is given (with ), where:
- If , then the edge is not present in the graph and can be added at a cost of .
- If , then the edge is present in the graph and can be removed at a cost of .
Bessie calls the following DFS routine starting from vertex :
[ \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 becomes a valid DFS order.
Observation: In order for to be a DFS order, there must be a DFS tree with the following chain of tree edges: , , ..., . With the freedom to choose the order in each adjacency list, it is sufficient to ensure that for each from to , the edge exists in the final graph. Any extra edge can be placed later in the adjacency order without affecting the DFS order.
Thus, for every , if the edge is absent initially (i.e. ), you must add it at a cost of . If , the edge is already present and no cost is incurred.
Compute the minimum total cost required so that is a valid DFS order.
inputFormat
The first line contains an integer (). This is followed by integers representing for every pair with . The integers for each are given in order for , separated by spaces or newlines.
outputFormat
Output a single integer: the minimum total cost to modify the graph so that is a valid DFS order.
sample
2
5
5
</p>