problem 1603-minimum Sum
Description
There is 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.
InputThere is multiple test cases.
First line of all case contains, 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 isn't larger than 1000000.OutputFor each test case and output minimum sum in a line. Sample Input4 2
5 1 7 10
5 3
1 8 6) 3 10
Sample Output2
8
Test Instructions:Give you n number, let you choose M number to make Sigma ABS (A[B[I]]-A[B[J]) when 1 <= i < j <= M. MinThe
following:After sorting, the number of consecutive m is selected because of the small range of numbers, we use bit optimization when statistics are continuous
#include <iostream>#include<cstdio>#include<cmath>#include<cstring>#include<algorithm>#include<queue>#include<vector>using namespacestd;Const intN = 1e5+Ten, M = -, mod = 1e9+9, INF = 1e9+9; typedefLong Longll;ll sum;intN,m,a[n]; intC[n],a[n]; intLowbit (intx) {returnx& (-x); } voidAddintXintadd) { for(; x < N; x + =lowbit (x)) {C[x]+=add; } } intSumsintx) {ints =0; for(; x >0; X-=lowbit (x)) {s+=C[x]; } returns; }intMain () { while(SCANF ("%d%d", &n,&m)! =EOF) {memset (C,0,sizeof(C)); for(intI=1; i<=n;i++) scanf ("%d",&A[i]); Sort (a+1, a+n+1); Sum=0; for(intI=1; i<=m;i++) {sum+ = (a[i]* (i-1)-sums (i)); Add (I,a[i]); } //cout<<sum<<endl;ll ans =sum; for(inti=m+1; i<=n;i++) {sum-= (sums (i)-sums (i-m)-a[i-m]* (M-1)); //cout<< (Sums (i)-sums (i-m+1)-a[i-m]* (m-1)) <<endl; //cout<<sum<<endl;Sum + = (a[i]* (M-1)-sums (i) +sums (i)m)); Add (I,a[i]); Ans=min (ans,sum); } printf ("%lld\n", ans); } return 0;}
Fifth session of Central China Programming Invitational and Wuhan University 14th session Network qualifier A Minimum Sum Tree Array