Delicious Apples
Time Limit: 5000/3000 MS (Java/Others) Memory Limit: 524288/524288 K (Java/Others)
Total Submission(s): 315 Accepted Submission(s): 92
Problem Description
There are
n apple trees planted along a cyclic road, which is
L metres long. Your storehouse is built at position
0 on that cyclic road.
The
i th tree is planted at position
xi , clockwise from position
0 . There are
ai delicious apple(s) on the
i th 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.
Input
First line:
t , the number of testcases.
Then
t testcases follow. In each testcase:
First line contains three integers,
L,n,K .
Next
n lines, each line contains
xi,ai .
Output
Output total distance in a line for each testcase.
Sample Input
2
10 3 2
2 2
8 2
5 1
10 4 1
2 2
8 2
5 1
0 10000
Sample Output
题目大意:
在一条环形通路上,有n棵苹果树,每棵苹果树有ai个苹果,求最少的行走距离用容量为k的篮子将苹果都运回起点。
解题思路:
比赛的时候想的方法跟题解一样,但是一直没想到怎么实现,先做的其他题,后来也没空做这道题了。在左右两边
的且可以装满整框的肯定运回离它最近的起点就可以了,还有可能越过中轴线才可以装满一筐,但是只有可能1次。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=200000+100;
long long dp1[maxn];
long long dp2[maxn];
int a[maxn],b[maxn];
int main()
{
int n,k,l,t;
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&l,&n,&k);
int cur1=0,cur2=0,u,v;
for(int i=0;i<n;i++)
{
scanf("%d%d",&u,&v);
for(int j=0;j<v;j++)
{
if(u*2<l)
a[++cur1]=u;
else
b[++cur2]=l-u;
}
}
sort(a+1,a+cur1+1);
sort(b+1,b+cur2+1);
memset(dp1,0,sizeof(dp1));
memset(dp2,0,sizeof(dp2));
for(int i=1;i<=cur1;i++)
{
if(i<=k)
dp1[i]=a[i];
else
dp1[i]=dp1[i-k]+a[i];
}
for(int i=1;i<=cur2;i++)
{
if(i<=k)
dp2[i]=b[i];
else
dp2[i]=dp2[i-k]+b[i];
}
long long ans=(dp1[cur1]+dp2[cur2])*2;
for(int i=0;i<=cur1&&i<=k;i++)
{
int le=cur1-i,re=max(0,cur2-(k-i));
ans=min(ans,l+(dp1[le]+dp2[re])*2);
}
printf("%I64d\n",ans);
}
return 0;
}