Delicious Apples
The ith tree is planted at position xi, clockwise from position 0. There are ai delicious apple(s) on the ith tree.
You only have a basket which can contain at most K apple(s). You are to start from your storehouse, pick all the apples and carry them back to your storehouse using your basket. What is your minimum distance travelled?
1≤n,k≤105,ai≥1,a1+a2+...+an≤105
1≤L≤109
0≤x[i]≤L
There are less than 20 huge testcases, and less than 500 small testcases.
Then t testcases follow. In each testcase:
First line contains three integers, L,n,K.
Next n lines, each line contains xi,ai.
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define M 100005
int Left[M],Right[M],numl,numr;
int n,k,l;
long long s_l[M],s_r[M],ans;
void slove()
{
for(int i=1;i<=numl;i++){
if(i<=k)
s_l[i]=Left[i];
else
s_l[i]=Left[i]+s_l[i-k];
}
for(int i=1;i<=numr;i++){
if(i<=k)
s_r[i]=Right[i];
else
s_r[i]=Right[i]+s_r[i-k];
}
ans=(s_r[numr]+s_l[numl])*2;
}
int main()
{
int T;
scanf("%d",&T);
while(T--){
scanf("%d%d%d",&l,&n,&k);
memset(s_l,0,sizeof(s_l));
memset(s_r,0,sizeof(s_r));
numl=numr=0;
for(int i=1;i<=n;i++){
int len,num;
scanf("%d%d",&len,&num);
for(int j=1;j<=num;j++){
if(len*2<l)
Left[++numl]=len;
else
Right[++numr]=l-len;
}
}
sort(Left+1,Left+1+numl);
sort(Right+1,Right+1+numr);
slove();
for(int i=0;i<=k;i++){
long long ll = 2*(s_l[numl-i]+s_r[max(0,numr-k+i)]);
ans=min(ans,ll+l);
}
printf("%lld\n",ans);
}
return 0;
}