#P6264. [COCI 2014/2015 #3] DOM

[COCI 2014/2015 #3] DOM

Description

In a nursing home, nn elderly people are watching TV. The TV program has mm channels, numbered from 11 to mm. Each elderly person has their own favorite and hated TV channels.

If the TV is showing a channel that an elderly person hates, they will stand up, slowly walk to the TV, change the channel to their favorite one, and then return to their comfortable chair. If multiple elderly people hate the current channel, the youngest among them will stand up and change the channel to their favorite, while everyone else stays seated.

Of course, after one channel change, another person may find the new channel unbearable, so they will change it again. Since the elderly people are stubborn, this may continue forever.

Given the favorite and hated channels of all elderly people, and the initial channel on the TV, determine how many channel changes are needed for everyone to stay happy.

Input Format

The first line contains three integers nn, mm, and pp, representing the number of elderly people in the nursing home, the number of TV channels, and the initial channel shown on the TV.

Each of the next nn lines contains two integers aia_i and bib_i, representing the favorite channel and the hated channel of each elderly person.

The elderly people are given in input order from youngest to oldest.

Output Format

Output one line containing the required number of channel changes. If the changes continue forever, output -1.

3 4 2
1 2
2 3
3 2
1
3 3 1
1 2
2 3
3 1
-1
4 5 2
1 3
2 3
3 2
5 1
3

Hint

Explanation of Sample Input/Output 1

Initially, the TV is on channel 22. This channel annoys the youngest and the oldest elderly person, so the youngest one stands up and changes the channel to their favorite, channel 11, and then everyone can watch channel 11 together.

Constraints

  • For 50%50\% of the testdata, it is guaranteed that 1n,m1031\le n,m\le 10^3.
  • For 100%100\% of the testdata, it is guaranteed that 1n,m1051\le n,m\le 10^5, 1pm1\le p\le m, 1ai,bim1\le a_i, b_i\le m, and aibia_i \neq b_i.

Translated by ChatGPT 5