Milking Order
InterviewTime limit2sMemory limit512 MB
Given a partial order between some cows and fixed positions for others, find the earliest position cow 1 can occupy.
- Level
Medium5 of 10
- Topics
- Topological sort, Greedy, Graph, Implementation
- Solved
- No attempts yet
Problem
Farmer John's cows (), numbered through as always, have too much time on their hooves. They have worked out a complex social structure around the order in which Farmer John milks them every morning. After weeks of study, Farmer John found that this structure rests on two properties.
First, because of the herd's social hierarchy, some cows insist on being milked before other cows, according to each cow's status. For example, if cow 3 has the highest status, cow 2 has average status, and cow 5 has low status, then cow 3 is milked first, cow 2 later, and cow 5 last.
Second, some cows only allow themselves to be milked at a certain position within the ordering. For example, cow 4 might insist on being milked second among all the cows.
Farmer John can always milk his cows in an order that satisfies all of these conditions.
Cow 1 has recently fallen ill, so Farmer John wants to milk her as early in the order as possible, so she can return to the barn and rest. Determine the earliest position cow 1 can take in the milking order.
Input
The first line contains , (), and (), meaning that Farmer John has cows, that of them have arranged themselves into a social hierarchy, and that of them demand a specific position in the order.
The next line contains distinct integers (). The cows on this line must be milked in the order in which they appear on the line.
Each of the next lines contains two integers () and (), meaning that cow must be milked in position .
A milking order satisfying all of these conditions always exists.
Output
Print the earliest position cow 1 can take in the milking order.
Hint
In the example, Farmer John has six cows and cow 1 is sick. He must milk cow 4 before cow 5 and cow 5 before cow 6. He must also milk cow 3 first and cow 5 third.
Cow 3 takes position 1, and since cow 4 comes before cow 5, cow 4 takes position 2 and cow 5 takes position 3. Cow 1 can therefore be fourth at the earliest.