Welcome to ZOJ
Information
Select Problem
Runs
Ranklist
ZOJ Problem Set - 3885
The Exchange of Items

Time Limit: 2 Seconds      Memory Limit: 65536 KB

Bob lives in an ancient village, where transactions are done by one item exchange with another. Bob is very clever and he knows what items will become more valuable later on. So, Bob has decided to do some business with villagers.

At first, Bob has N kinds of items indexed from 1 to N, and each item has Ai. There are M ways to exchanges items. For the ith way (Xi, Yi), Bob can exchange one Xith item to one Yith item, vice versa. Now Bob wants that his ith item has exactly Bi, and he wonders what the minimal times of transactions is.

Input

There are multiple test cases.
For each test case: the first line contains two integers: N and M (1 <= N, M <= 100).
The next N lines contains two integers: Ai and Bi (1 <= Ai, Bi <= 10,000).
Following M lines contains two integers: Xi and Yi (1 <= Xi, Yi <= N).
There is one empty line between test cases.

Output

For each test case output the minimal times of transactions. If Bob could not reach his goal, output -1 instead.

Sample Input

2 1
1 2
2 1
1 2

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

Sample Output

1
-1

Author: FENG, Jingyi
Source: ZOJ Monthly, July 2015
Submit    Status