← 返回 amazon 的题目列表Build Order for a Target Package
类型:online_judge
Return the Complete Build Order for a Target Package
Given package dependency relations and a target package name x, return the complete build order required to build x.
A relation A B means that package A depends on package B to be built. The result must contain only x, its direct dependencies, and its transitive dependencies. Every package must appear after all of its dependencies.
If a cyclic dependency is reachable from x, the build cannot be completed; return an empty list.
Use DFS and detect cycles with these states:
visiting: the package is on the current DFS path;
visited: the package and all of its dependencies have been fully processed.
Input Format (for this problem)
First line: integer n, the number of dependency relations.
Next n lines: package dependency, meaning package depends on dependency.
Final line: target package name x.
Output Format
If acyclic: print one valid build order with package names separated by spaces.
If cyclic: print an empty line.
Example
Input:
5
web api
web frontend
api database
frontend shared-ui
shared-ui assets
web
Output:
database api assets shared-ui frontend web
Constraints
1 <= n <= 2 * 10^5
Let the target-reachable subgraph contain V packages and E dependency edges.
Example
Input
5
web api
web frontend
api database
frontend shared-ui
shared-ui assets
web
Output
database api assets shared-ui frontend web