Kuru Kuru Sushi
Time limit5sMemory limit512 MB
Orient each conveyor on a cycle so all q food transfers are possible, then print the minimum total shortest-path cost, or -1.
- Level
Medium7 of 10
- Topics
- Graph, Segment tree, Shortest path
- Solved
- No attempts yet
Problem
Zephir is the owner of the kuru kuru sushi restaurants. In these restaurants, sushi is placed on a rotating circular belt conveyor and delivered to customers.
Zephir owns restaurants numbered from 0 to . The restaurants are placed on the circumference of a circle, and a large belt conveyor runs underground between each pair of adjacent restaurants. One day, some restaurants ran short of sushi ingredients, so he decided to transport ingredient foods between restaurants using these conveyors.
The -th () belt conveyor connects restaurants and . The -th belt conveyor connects restaurants and . The length of the -th conveyor is . He wants to transport foods, where the -th food is transported from restaurant to restaurant .
Each conveyor can transport food in only one direction, and Zephir can choose that direction. The directions cannot change while all foods are being transported. The transportation cost of the -th food is the sum of the lengths of the conveyors on the shortest path from to . Zephir must set the direction of every conveyor so that all foods can be transported. Calculate the minimum total cost, which is the sum of the transportation costs of all foods.
Input
The first line contains two integers and . Here () is the number of restaurants, and () is the number of foods. The next line contains integers (). Each of the following lines contains two integers and (). It is guaranteed that for every , and that or for every pair .
$n$ $q$
$w_0$ $w_1$ ... $w_{n-1}$
$s_0$ $t_0$
...
$s_{q-1}$ $t_{q-1}$
Output
Print the minimum total cost of the food transportation. If it is impossible to transport all foods to their destinations, print -1.