UberOA #51
Minimum Edge Reversals to Root a Tree
Estimated HardJudge-ready
Topics (AI-labelled)Union-FindDP Basics
You are given a tree where every edge currently has a direction. Choose any node as the root; all edges must end up pointing away from the root. Reversing one edge costs 1. Find the minimum total cost.
This site has made the standard input and output explicit.
Input
The first line contains n, followed by n−1 lines of directed edges u v, 0-based. On this site 1≤n≤200000, and ignoring directions the graph must be a tree.
Output
Output one integer, the answer.
Example 1
Input:
3
0 1
2 1
Output:
1
Example 2
Input:
3
0 1
1 2
Output:
0
Example 3
Input:
1
Output:
0
Example notes
Example 1: whether 0 or 2 is the root, only 1 edge needs reversing, so the minimum is 1. Example 2: with 0 as the root all edges already point outward, so output 0. Example 3: there are no edges, so nothing needs reversing.
Editorial
Loading solution…