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;
}

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

被折叠的 条评论
为什么被折叠?



