洛谷P3143 Diamond Collector S

题目描述

Bessie the cow, always a fan of shiny objects, has taken up a hobby of mining diamonds in her spare time! She has collected NN diamonds (N \leq 50,000N≤50,000) of varying sizes, and she wants to arrange some of them in a pair of display cases in the barn.

Since Bessie wants the diamonds in each of the two cases to be relatively similar in size, she decides that she will not include two diamonds in the same case if their sizes differ by more than KK (two diamonds can be displayed together in the same case if their sizes differ by exactly KK). Given KK, please help Bessie determine the maximum number of diamonds she can display in both cases together.

奶牛Bessie很喜欢闪亮亮的东西(Baling~Baling~),所以她喜欢在她的空余时间开采钻石!她现在已经收集了N颗不同大小的钻石(N<=50,000),现在她想在谷仓的两个陈列架上摆放一些钻石。

Bessie想让这些陈列架上的钻石保持相似的大小,所以她不会把两个大小相差K以上的钻石同时放在一个陈列架上(如果两颗钻石的大小差值为K,那么它们可以同时放在一个陈列架上)。现在给出K,请你帮Bessie确定她最多一共可以放多少颗钻石在这两个陈列架上。

输入格式

The first line of the input file contains NN and KK (0 \leq K \leq 1,000,000,0000≤K≤1,000,000,000).

The next NN lines each contain an integer giving the size of one of the

diamonds. All sizes will be positive and will not exceed 1,000,000,0001,000,000,000.

输出格式

Output a single positive integer, telling the maximum number of diamonds that

Bessie can showcase in total in both the cases.

输入输出样例

输入 #1复制

7 3
10
5
1
12
9
5
14

输出 #1复制

5

上代码:

#include<cstdio>
#include<algorithm>
using namespace std;
int n,k,a[50005],c[50005],r=2,ma,ans;//c[i]用来存从i-1向左最多可以取多少颗钻石。 
int main(){
    scanf("%d %d",&n,&k);
    a[n+1]=2100000000;//立个哨兵,防止r"跑丢"... 
    for(int i=1;i<=n;++i)
        scanf("%d",&a[i]);
    sort(a+1,a+n+1);
    for(int i=1;i<=n;++i){
        while(a[r]<=a[i]+k)r++;//可以往右就尽量往右,因为我们只需要最长的。 
        c[r]=max(r-i,c[r]);
        ma=max(ma,c[i]);//记录第i颗钻石(不包括i)前可以摆最多的钻石。即第一个架子上的钻石。 
        ans=max(ans,ma+r-i);//为什么是'r-i'而不是'c[r]'? 因为要防区间重叠.qwq
    }
    printf("%d",ans);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值