CF2165A.Cyclic Merging

普及-

通过率:0%

时间限制:2.00s

内存限制:256MB

AC君温馨提醒

该题目为【codeforces】题库的题目,您提交的代码将被提交至codeforces进行远程评测,并由ACGO抓取测评结果后进行展示。由于远程测评的测评机由其他平台提供,我们无法保证该服务的稳定性,若提交后无反应,请等待一段时间后再进行重试。

题目描述

You are given nn non-negative integers a1,a2,…,ana_1,a_2,\ldots,a_n arranged on a ring. For each 1≤i<n1\le i \lt n, aia_i and ai+1a_{i+1} are adjacent; a1a_1 and ana_n are adjacent.

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

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

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

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

给你 nn 个非负整数 a1,a2,…,ana_1,a_2,\ldots,a_n,它们按环形排列。对于每个 1≤i<n1\le i \lt n,aia_i 与 ai+1a_{i+1} 相邻;a1a_1 与 ana_n 相邻。

你需要恰好执行以下操作 n−1n-1 次:

  • 在环上任选一对相邻元素,设其值分别为 xx 和 yy,将它们合并为一个值为 max⁡(x,y)\max(x,y) 的新元素,此次合并的代价为 max⁡(x,y)\max(x,y)。

注意:该操作会使环的大小减少 11,并相应地更新相邻关系。

请计算将整个环合并为单个元素所需的最小总代价。

输入格式

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

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

The following line contains nn integers a1,a2,…,ana_1,a_2,\ldots,a_n (0≤ai≤1090\le a_i \le 10^9).

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

每个测试包含多个测试用例。第一行包含测试用例的数量 tt(1≤t≤1041 \le t \le 10^4)。随后是各测试用例的描述。

每个测试用例的第一行包含一个整数 nn(2≤n≤2⋅1052\le n\le 2\cdot 10^5)。

接下来的一行包含 nn 个整数 a1,a2,…,ana_1,a_2,\ldots,a_n(0≤ai≤1090\le a_i \le 10^9)。

保证所有测试用例的 nn 之和不超过 2⋅1052\cdot 10^5。

输出格式

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

对于每个测试用例,请输出一个整数——最小总成本。

输入输出样例

  • 输入#1

    3
    4
    1 1 3 2
    2
    0 2
    7
    1 1 4 5 1 4 1

    输出#1

    6
    2
    19

说明/提示

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

  • Merge indexes 11 and 22 with a cost of 11, the ring becomes [1,3,2][1,3,2].
  • Merge indexes 11 and 33 with a cost of 22, the ring becomes [3,2][3,2].
  • Merge indexes 11 and 22 with a cost of 33, the ring becomes [3][3].

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

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

在第一个测试用例中,我们可以在序列 [1,1,3,2][1,1,3,2] 上实现总代价为 66,具体步骤如下:

  • 合并下标 11 和 22,代价为 11,环变为 [1,3,2][1,3,2];
  • 合并下标 11 和 33,代价为 22,环变为 [3,2][3,2];
  • 合并下标 11 和 22,代价为 33,环变为 [3][3]。

总代价为 1+2+3=61+2+3=6。可以证明无法获得更低的代价;因此答案确为 66。

在第二个测试用例中,唯一的选择是合并两个元素,代价为 22。

输入解题思路,AI测评打分。不知道怎么写?

首页