Problem 1603 - Minimum Sum
Time Limit: 2000MS Memory Limit: 65536KB
Total Submit: 564 Accepted: 157 Special Judge: No
Description
There are n numbers A[1] , A[2] .... A[n], you can select m numbers of it A[B[1]] , A[B[2]] ... A[B[m]] ( 1 <= B[1] < B[2] .... B[m] <= n ) such that Sum as small as possible.
Sum is sum of abs( A[B[i]]-A[B[j]] ) when 1 <= i < j <= m.
Input
There are multiple test cases.
First line of each case contains two integers n and m.( 1 <= m <= n <= 100000 )
Next line contains n integers A[1] , A[2] .... A[n].( 0 <= A[i] <= 100000 )
It‘s guaranteed that the sum of n is not larger than 1000000.
Output
For each test case, output minimum Sum in a line.
Sample Input
4 2
5 1 7 10
5 3
1 8 6 3 10
Sample Output
2
8
题意: 长度为n的数组A 任意取 取出的数量为m 然后求 所有 abs( A[B[i]]-A[B[j]] i<j ) 的和
题解: 比赛的时候 有一个思路 题目时间限制是2000ms 但woj 测评 2000+ms 过了
先sort排序 取连续出长度为m的序列re[] 求其sum值
预处理求 re[1]-re[2] =ans[2] 并记录前缀和
re[1]-re[3] =ans[3]
...
re[1]-re[m]=ans[m]
re[2]-re[3]=(re[1]-re[3])-(re[1]-re[2]) //
re[2]-re[4]=(re[1]-re[4])-(re[1]-re[2]) //将要求的量 转化为已知量