#P9834. [USACO05OPEN] Around the world G

[USACO05OPEN] Around the world G

Problem Description

In recent years, Farmer John has made many friends around the world who also run farms. Since he has not visited Ted the farmer in the UK and Boor the farmer in the Netherlands for a while, he wants to go and visit them.

He knows the longitude of each friend’s farm (an integer from 00 to 359359). We treat the Earth as a circle, and longitudes increase clockwise along this circle.

Farmer John plans to travel by plane to visit his nn friends (numbered from 11 to nn). He knows there are mm bidirectional flight routes between these farms. The plane always flies along the shortest path on the surface (that is, the shorter arc on the circle). Every route between two farms must be along the shortest arc.

It is guaranteed that if two farms are at opposite ends of a diameter, then there will not be a direct route connecting them.

Therefore, any single trip can be described as either clockwise or counterclockwise. For example, going from longitude 3030 to longitude 3535 is clockwise; going from longitude 350350 to longitude 1010 is also clockwise; while going from longitude 350350 to longitude 200200 is counterclockwise.

To look cool, Farmer John decides to make a round-the-world trip by passing through some of his friends’ farms. He wants to know whether this is possible, and if it is, the minimum number of flights needed.

He wants to start and end this trip at his best friend’s farm (the first one in the input). To ensure this is a round-the-world journey, when the trip ends, the total clockwise distance traveled must not be equal to the total counterclockwise distance traveled.

Input Format

The first line contains two integers nn and mm, separated by spaces.

Lines 22 to n+1n+1: line i+1i+1 contains one integer, the longitude of farm ii. The second line is the address of his best friend.

Lines n+2n+2 to n+m+1n+m+1: line i+n+1i+n+1 contains two integers, indicating that there is a route between these two farms.

Output Format

Output one integer: the minimum number of flights Farmer John must take to complete the round-the-world trip. Each time Farmer John travels from one farm to another counts as one flight. If it is impossible to make a round-the-world trip, output -1.

3 3
0
120
240
1 2
2 3
1 3

3

Hint

For 100%100\% of the testdata, 1n5×1031 \leq n \leq 5 \times 10^3 and 1m2.5×1041 \leq m \leq 2.5 \times 10^4.

Translated by ChatGPT 5