766. Carpool to the Capital
A company has offices in n cities numbered 0 to n - 1, and city 0 is the capital. The cities are joined by n - 1 two-way roads, so there is exactly one route between any two cities; roads[i] = [a, b] describes one road, and n = roads.length + 1. Every city except the capital has one employee who must get to the capital for a meeting.
Each city owns one car with seats seats (the driver counts as a seat). A car may pick up employees in cities it passes through, and an employee may switch cars in any city. Driving one car along one road uses exactly one liter of fuel. Return the minimum total liters needed to bring all employees to the capital.
Example 1
- Input:
- roads = [[0,1],[1,2],[2,3],[3,4]], seats = 2
- Output:
- 6
- Explanation:
The roads carry 4, 3, 2 and 1 riders respectively; with 2 seats they need 2 + 2 + 1 + 1 = 6 liters.
Example 2
- Input:
- roads = [[0,1],[1,2],[1,3],[1,4]], seats = 3
- Output:
- 5
- Explanation:
The three outer roads need 1 liter each and the road into the capital carries 4 riders, which needs 2 cars: 3 + 2 = 5.
Example 3
- Input:
- roads = [[0,1],[0,2],[0,3]], seats = 8
- Output:
- 3
- Explanation:
Each of the three cities sends one car directly, so 3 liters are used.
Constraints
- 0 ≤ roads.length ≤ 105 (so n = roads.length + 1 ≤ 100001)
- 0 ≤ a, b < n and the roads form a tree
- 1 ≤ seats ≤ 105
- The answer may exceed 32 bits; return a 64-bit integer.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 200 msC++ 50 msJava 100 msJavaScript 100 msTypeScript 100 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)