## DMOPC '22 Contest 1 P2 - Hat Swap

View as PDF

Points: 10 (partial)
Time limit: 2.0s
Memory limit: 256M

Author:
Problem type

There are people in Shirogane's class, each with a coloured hat of colour . Shirogane is person number , and Kaguya is person . People with the same colour of hat get to be in the same group, so naturally Shirogane wants to ensure that him and Kaguya end up in the same group.

It seems that there are pairs of people willing to trade hats. What is the minimum number of trades Shirogane must perform to ensure he and Kaguya end up in the same group?

#### Constraints

Each unordered pair in the input is listed only once.

#### Input Specification

The first line contains two integers, and .

The next line contains integers, the th of which is .

The next lines contain two integers each, a pair of people that are willing to swap.

#### Output Specification

If it is impossible to put Shirogane and Kaguya in the same group, output .

Otherwise, output the minimum number of swaps required such that Shirogane and Kaguya end up in the same group.

#### Sample Input 1

4 3
1 2 2 3
1 2
2 3
3 4

#### Sample Output 1

2

#### Explanation for Sample 1

By performing the swap and the swap , Kaguya and Shirogane end up with the same hat colour.

#### Sample Input 2

2 1
1 2
1 2

#### Sample Output 2

-1