HDU 5303 Delicious Apples (2015多校第二场 贪心 + 枚举)

解决一个关于沿环形路径摘取苹果并返回仓库的问题,通过贪心算法与枚举策略结合,实现最小路径长度的计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Delicious Apples

Time Limit: 5000/3000 MS (Java/Others)    Memory Limit: 524288/524288 K (Java/Others)
Total Submission(s): 321    Accepted Submission(s): 95


Problem Description
There are  apple trees planted along a cyclic road, which is  metres long. Your storehouse is built at position  on that cyclic road.
The th tree is planted at position , clockwise from position . There are  delicious apple(s) on the th tree.

You only have a basket which can contain at most  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?





There are less than 20 huge testcases, and less than 500 small testcases.
 

Input
First line: , the number of testcases.
Then  testcases follow. In each testcase:
First line contains three integers, .
Next  lines, each line contains .
 

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
18 26
 
解题思路:
注意到,最多仅仅有一次会绕整个圈走一次。因此,先贪心的处理左半环和右半环。然后枚举绕整圈的时候从左側摘得苹果和从右側摘得苹果的数目。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <algorithm>
#define LL long long
using namespace std;
const int MAXN = 100000 + 10;
int L, N, K;
LL x[MAXN];
LL ld[MAXN], rd[MAXN];
vector<LL>l, r;
int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        scanf("%d%d%d", &L, &N, &K);
        l.clear(); r.clear();
        int pos, num, m = 0;
        for(int i=1;i<=N;i++)
        {
            scanf("%d%d", &pos, &num);
            for(int i=1;i<=num;i++)
                x[++m] = (LL)pos;
        }
        for(int i=1;i<=m;i++)
        {
            if(2 * x[i] < L) l.push_back(x[i]);
            else r.push_back(L - x[i]);
        }
        sort(l.begin(), l.end()); sort(r.begin(), r.end());
        int lsz = l.size(), rsz = r.size();
        memset(ld, 0, sizeof(ld)); memset(rd, 0, sizeof(rd));
        for(int i=0;i<lsz;i++)
            ld[i + 1] = (i + 1 <= K ? l[i] : ld[i + 1 - K] + l[i]);
        for(int i=0;i<rsz;i++)
            rd[i + 1] = (i + 1 <= K ? r[i] : rd[i + 1 - K] + r[i]);
        LL ans = (ld[lsz] + rd[rsz]) * 2;
        for(int i=0;i<=lsz&&i<=K;i++)
        {
            int p1 = lsz - i;
            int p2 = max(0, rsz-(K-i));
            ans = min(ans, 2*(ld[p1] + rd[p2]) + L);
        }
        cout << ans << endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值