DFS Order
Time limit2sMemory limit2048 MB
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 to (). 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] () 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 with , you are given an integer ().
- If , edge is not in the graph and can be added for cost .
- If , edge is in the graph and can be removed for cost .
Find the minimum total cost to change the graph so that is a possible DFS order.
Input
The first line contains . Then lines follow. The th line contains , separated by spaces.
Output
Print the minimum total cost to change the graph so that is a possible DFS order.