Operation Permutation
InterviewTime limit1sMemory limit1024 MB
Find the smallest number of reported pairs after which the order of soldiers is uniquely determined, or -1 if it never becomes unique.
- Level
Medium5 of 10
- Topics
- Topological sort, Graph, Binary search
- Solved
- No attempts yet
Problem
General Petrov loves drill practice more than anything. Once, soldiers, numbered from to for simplicity, took part in a formation. The soldiers lined up in a row, and the soldier at position had number . Afterward, the general's adjutant walked along the line and confirmed that the order matched the one the general had chosen.
Some time later, the general wanted to arrange the soldiers in the same order again. However, he forgot how he had arranged them the first time. Fortunately, the adjutant has a good memory: for pairs of positions , he remembers that the number of the soldier at position is less than the number of the soldier at position .
The adjutant reports the pairs one at a time. The general wants to start arranging the soldiers quickly, though. Find the minimum such that, once the adjutant has reported the first pairs, the general can uniquely determine the desired permutation.
Input
The first line contains two integers and : the number of soldiers in the operation and the number of position pairs the adjutant remembers (; ).
Each of the next lines contains a pair , in the order the adjutant reports them. It means the soldier number at position is less than the soldier number at position (; ).
Each pair appears at most once. The input is guaranteed to be consistent: at least one permutation satisfies all the remembered conditions.
Output
Print one integer , the smallest index of a pair after which the permutation can be uniquely restored. If the permutation cannot be uniquely restored, print .
Hint
In the first example, the soldiers stood in the order . The order can be restored already after the fourth remembered pair.
In the second example, four arrangements satisfy the input: , , , and .