codeforces题目之1175 D. Array Splitting

题目

D. Array Splitting
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given an array a1,a2,…,an and an integer k.
You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let f(i) be the index of subarray the i-th element belongs to. Subarrays are numbered from left to right and from 1 to k.
Let the cost of division be equal to ∑i=1n(ai⋅f(i)). For example, if a=[1,−2,−3,4,−5,6,−7] and we divide it into 3 subbarays in the following way: [1,−2,−3],[4,−5],[6,−7], then the cost of division is equal to 1⋅1−2⋅1−3⋅1+4⋅2−5⋅2+6⋅3−7⋅3=−9.
Calculate the maximum cost you can obtain by dividing the array a into k non-empty consecutive subarrays.

Input
The first line contains two integers n and k (1≤k≤n≤3⋅105).
The second line contains n integers a1,a2,…,an (|ai|≤106).

Output
Print the maximum cost you can obtain by dividing the array a into k nonempty consecutive subarrays.

Examples
input

5 2
-1 -2 5 -4 8

output

15

input

7 6
-3 0 -1 -2 -2 -4 -1

output

-45

input

4 1
3 -1 6 0

output

8

题目理解

题目提供一个乱序的数字序列,需要将他分成k份,第i份的数均乘以i,然后将所有的子序列都相加。求最佳的分割方法可以得到最大值。

答题思路

将每个数乘以i视为被加过i次,从一开始,所有的数就会被加过一次,当分割一次后,分割后的所有数就会被加过一次。例如题目的实例[1,−2,−3,4,−5,6,−7] 分割为[1,−2,−3],[4,−5],[6,−7],一开始所有的数都加一次,然后在-3后分割一次,那么4、-5、6、-7则会被再加一次,累计两次,在-5后分割时,6、-7又被加了一次,累计三次。与分别乘以1、2、3得到相同结果。

  1. 从后往前,将每个数到最后一个数的和存储;
  2. 因为所有的数必定被加过一次,所以将第一个数到最后一个数的和先加上。
  3. 对所有和(除了第一个数的)进行升序排序,加上前k-1个和数即为答案。

代码如下(python)

n, k = map(int, input().strip().split(' '))
a = list(map(int, input().strip().split(' ')))
cnt = []
cnt.append(a[-1])
for i in range(1, n):
 cnt.append(cnt[i-1] + a[-(i+1)])
ans = cnt[-1]
del cnt[-1]
cnt.sort(reverse=True)
ans += sum(cnt[:(k-1)])
print(ans)

代码解析

cnt.sort(reverse=True)

reverse=True表示排序使用升序排序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值