#P10123. [USACO18OPEN] Milking Order B
[USACO18OPEN] Milking Order B
Problem Description
Farmer John’s cows (), conveniently numbered , have been feeling bored. So, they have developed a complex social structure related to the order they line up in each morning when Farmer John milks them. After several weeks of study, Farmer John has found that this structure is based on two key properties.
First, because of the cows’ social ranks, some cows insist on being milked before other cows, based on their rank. For example, if cow has the highest rank, cow is in the middle, and cow is low-ranked, then cow must be milked first, then cow , and finally cow .
Second, some cows will only allow themselves to be milked at a specific position in the line. For example, cow might insist on being the second cow to be milked out of all the cows.
Fortunately, Farmer John can always milk his cows in an order that satisfies all of these conditions.
Unfortunately, cow has recently become sick, so Farmer John wants to milk her as early as possible, so she can return to the barn for some much-needed rest. Please help Farmer John determine the earliest possible position where cow can appear in the milking order.
Input Format
The first line contains , (), and (), meaning Farmer John has cows, of which form a social hierarchy, and must be in specific positions in the milking order. The next line contains distinct integers (). The cows listed on this line must be milked in the same relative order as they appear in this line. The following lines each contain two integers () and (), meaning cow must be milked in position .
The input guarantees that under these constraints, Farmer John can construct a milking order that satisfies all requirements.
Output Format
Output the earliest possible position where cow can appear in the milking order.
6 3 2
4 5 6
5 3
3 1
4
Hint
In this example, Farmer John has six cows, and cow is sick. His milking order must have cow before cow , and cow before cow . Also, Farmer John must milk cow first, and cow third.
Since FJ must milk cow first, and because cow must be before cow , cow has to be milked second, and then cow third. Therefore, the earliest possible position for cow in the milking order is fourth.
Translated by ChatGPT 5