가중치가 있는 원형 그래프의 각 간선 방향을 정해 q개의 출발지-도착지 쌍에 대한 최단 경로 길이 합을 최소화하고, 불가능하면 -1을 출력한다.
어려움8그래프그리디누적 합구현아직 제출이 없습니다시간 제한5초메모리 제한512 MBZephir is an owner of the “kuru kuru sushi” restaurants. In these restaurants, sushis are placed on a rotating circular belt conveyor and delivered to customers.
Zephir owns n restaurants numbered from 0 to n−1. Due to his passion for rotation, these restaurants are placed on the circumference of a circle, and have huge belt conveyors under the ground between adjacent restaurants. One day, the ingredients of sushis were short in some restaurants. Therefore, he decided to transport some ingredient foods between restaurants by using these belt conveyors.
The i-th (0≤i≤n−2) belt conveyor connects the restaurants i and i+1. The (n−1)-th belt conveyor connects the restaurants n−1 and 0. The length of the i-th belt conveyor is w_i. He wants to transport q foods from some restaurants to other restaurants. The i-th food should be transported from restaurant s_i to t_i.
Zephir wants to minimize the total cost of transportation. The transportation cost of each food can be changed by the settings of the direction of the belt conveyors. Each belt conveyor can transport foods in only a single direction, which can be set by Zephir. Moreover, the settings cannot be changed while transporting all q foods. The transportation cost of the i-th food is the sum of the length of the belt conveyors in the shortest path from restaurant s_i to t_i. He should set the direction of belt conveyors to transport all foods. Write a program to calculate the minimum value of the total cost, which is the sum of the transportation costs of all the q foods.
Each input is formatted as follows:
$n$ $q$
$w_0$ $w_1$ ... $w_{n-1}$
$s_0$ $t_0$
...
$s_{q-1}$ $t_{q-1}$
The first line contains two integers n and q. n (3≤n≤105) denotes the number of the restaurants, and q (1≤q≤105) denotes the number of the foods to transport. The next line contains n integers. w_i (1≤w_i≤105) denotes the length of the i-th belt conveyor. Each of the following q lines contains two integers s_i (0≤s_i≤n−1) and t_i (0≤t_i≤n−1). Each denotes the i-th food should be transported from restaurant s_i to t_i. You may assume s_i=t_i for any 0≤i≤q−1, and s_i=s_j or t_i=t_j if i=j for any 0≤i,j≤q−1.
Print the minimum total cost of the foods transportation. If it is impossible to transport all foods to each destination, print -1.