Kingdom's Development Plan
InterviewTime limit2sMemory limit1024 MB
Given n projects and prerequisite pairs, output the lexicographically smallest valid completion order, or IMPOSSIBLE if the dependencies contain a cycle.
- Level
Easy3 of 10
- Topics
- Topological sort, Graph, Heap
- Solved
- No attempts yet
Problem
The Kingdom of Topcaria is planning a series of developmental projects to enhance its infrastructure. Each project has prerequisites that must be completed before it can start. The Ministry of Development wants you to find a feasible order in which all the projects can be completed.
You are given:
- , the number of projects, numbered from 1 to .
- , the number of prerequisite relationships.
- pairs , each meaning project must be completed before project can start.
If all projects cannot be completed because of a cyclic dependency, output IMPOSSIBLE. If several valid orders exist, output the lexicographically smallest one.
Input
The first line contains two integers and . Each of the next lines contains two integers and , a prerequisite pair meaning project must be completed before project .
Output
If it is impossible, output IMPOSSIBLE. Otherwise, output one line with integers, a valid completion order. If several orders are valid, output the lexicographically smallest one. An order is smaller than another if, at the first position where they differ, its project number is smaller.
Constraints
- No duplicate pairs are given.