lightoj 1084 - Winter

本文探讨了一群人在直线路径上如何在限定距离内形成至少三人一组的团队以抵御寒冷的问题,采用动态规划算法求解最小团队数量。

Winter is coming. In a land far away, N men are spending the nights in a valley in a largest field. The valley is so narrow that it can be considered to be a straight line running east-to-west.

Although standing in the valley does shield them from the wind, the group still shivers during the cold nights. They, like anyone else, would like to gather together for warmth.

Near the end of each day, each man i finds himself somewhere in the valley at a unique location Li. The men want to gather into groups of three or more persons since two persons just aren't warm enough. They want to be in groups before sunset, so the distance K each man can walk to form a group is limited. Determine the smallest number of groups the men can form.

Input

Input starts with an integer T (≤ 15), denoting the number of test cases.

Each case starts with two integers N (1 ≤ N ≤ 105) and K (1 ≤ K ≤ 106). Each of the next N line contains an integer Li (1 ≤ Li ≤ 108).

Output

For each case, print the case number and smallest number of groups the men can gather into. If there is no way for all the men to gather into groups of at least size three, output -1.

Sample Input

Output for Sample Input

2

6 10

2

10

15

13

28

9

3 1

1 10 20

Case 1: 2

Case 2: -1



大意是一群人在一条直线上,他们要抱成三个或以上人数的团,但是他们只能走k米,问最少组成多少个团,如果有落单的就输出-1。

一个很神奇的DP(我认为。。。),dp[i]表示以i为左边界的最少团数。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define inf 1e9
using namespace std;

int main(void)
{
    int T,n,k,i;
    int a[100010];
    int dp[100010];
    scanf("%d",&T);
    int cas = 1;
    while(T--)
    {
        scanf("%d%d",&n,&k);
        for(i=0;i<n;i++)
            scanf("%d",&a[i]);
        sort(a,a+n);
        dp[n] = 0;
        for(i=n-1;i>=0;i--)
        {
            dp[i] = inf;
            int x = upper_bound(a,a+n,a[i]+2*k) - a;
            if(x - i >= 3)
                dp[i] = min(dp[i],dp[x] + 1);
            if(x - i >= 4)//可以分给右边的团一个人
                dp[i] = min(dp[i],dp[x-1] + 1);
            if(x - i >= 5)//可以分给右边的团两个人
                dp[i] = min(dp[i],dp[x-2] + 1);
        }
        printf("Case %d: ",cas++);
        if(dp[0] == inf)
            printf("-1\n");
        else
            printf("%d\n",dp[0]);
    }

    return 0;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值