#P10123. [USACO18OPEN] Milking Order B

[USACO18OPEN] Milking Order B

Problem Description

Farmer John’s NN cows (2N1002\le N\le 100), conveniently numbered 1N1\ldots N, 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 33 has the highest rank, cow 22 is in the middle, and cow 55 is low-ranked, then cow 33 must be milked first, then cow 22, and finally cow 55.

Second, some cows will only allow themselves to be milked at a specific position in the line. For example, cow 44 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 11 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 11 can appear in the milking order.

Input Format

The first line contains NN, MM (1M<N1\le M<N), and KK (1K<N1\le K<N), meaning Farmer John has NN cows, of which MM form a social hierarchy, and KK must be in specific positions in the milking order. The next line contains MM distinct integers mim_i (1miN1\le m_i\le N). The cows listed on this line must be milked in the same relative order as they appear in this line. The following KK lines each contain two integers cic_i (1ciN1\le c_i\le N) and pip_i (1piN1\le p_i\le N), meaning cow cic_i must be milked in position pip_i.

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 11 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 11 is sick. His milking order must have cow 44 before cow 55, and cow 55 before cow 66. Also, Farmer John must milk cow 33 first, and cow 55 third.

Since FJ must milk cow 33 first, and because cow 44 must be before cow 55, cow 44 has to be milked second, and then cow 55 third. Therefore, the earliest possible position for cow 11 in the milking order is fourth.

Translated by ChatGPT 5