Codeforces Round 1064 (Div. 2)
C
Cyclic Merging
Codeforces
未评级
原题
← BD →
翻译中…

You are given $n$ non-negative integers $a_1,a_2,\ldots,a_n$ arranged on a ring. For each $1\le i \lt n$, $a_i$ and $a_{i+1}$ are adjacent; $a_1$ and $a_n$ are adjacent.

翻译中…

You need to perform the following operation exactly $n-1$ times:

翻译中…
  • Choose any pair of adjacent elements on the ring, let their values be $x$ and $y$, and merge them into a single element of value $\max(x,y)$ with cost $\max(x,y)$.
翻译中…

Note that this operation will decrease the size of the ring by $1$ and update the adjacent relationships accordingly.

翻译中…

Please calculate the minimum total cost to merge the ring into one element.

翻译中…

Input

翻译中…

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$). The description of the test cases follows.

翻译中…

The first line of each test case contains an integer $n$ ($2\le n\le 2\cdot 10^5$).

翻译中…

The following line contains $n$ integers $a_1,a_2,\ldots,a_n$ ($0\le a_i \le 10^9$).

翻译中…

It is guaranteed that the sum of $n$ over all test cases does not exceed $2\cdot 10^5$.

翻译中…

Output

翻译中…

For each test case, please print a single integer — the minimum total cost.

翻译中…

Note

翻译中…

In the first test case, we can achieve a cost of $6$ on $[1,1,3,2]$ as follows:

翻译中…
  • Merge indexes $1$ and $2$ with a cost of $1$, the ring becomes $[1,3,2]$.
  • Merge indexes $1$ and $3$ with a cost of $2$, the ring becomes $[3,2]$.
  • Merge indexes $1$ and $2$ with a cost of $3$, the ring becomes $[3]$.
翻译中…

The total cost is $1+2+3=6$. It can be proven that it is impossible to achieve a lower cost; thus, the answer is indeed $6$.

翻译中…

In the second test case, the only option is to merge the two elements, with a cost of $2$.

翻译中…

样例

Input #1
3
4
1 1 3 2
2
0 2
7
1 1 4 5 1 4 1
Output #1
6
2
19
InputCopy OutputCopy
题目信息
题号
2166C
时间限制
2 s
内存限制
256 MB

题面与样例版权归 Codeforces 及出题人所有;中文翻译由 AI 生成(CI 管线),如有出入请以原文为准。