cswork / OAOpen practice workspace

AmazonOA #112

Circular Route Query Distance

Estimated EasyJudge-ready

Topics (AI-labelled)Prefix & Ranges

distances[i] connects station i and station (i+1) modulo n. Each query is an independent start and end; take the shorter of the clockwise and counterclockwise distances, then sum over all queries.

Input

The first line contains n q, the second line contains n edge lengths, followed by q lines of 0-based start and end stations. The original gives no value ranges; this site sets 1≤n,q≤100000, 1≤(edge length)≤10⁹.

Output

Output a single integer answer.

Example 1

Input:

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

Output:

10

Example 2

Input:

4 2
7 10 1 12
0 2
2 1

Output:

23

Example 3

Input:

1 1
9
0 0

Output:

0

Example notes

Example 1: the shortest distances are 1, 5 and 4, for a total of 10. Example 2: 0 to 2 goes the other way for 13, and 2 to 1 is 10, for a total of 23. Example 3: the same station needs no movement, for a total of 0.

Editorial

Loading solution…