洛谷P3143 [USACO16OPEN]钻石收藏家Diamond Collector

Posted SilverNebula

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了洛谷P3143 [USACO16OPEN]钻石收藏家Diamond Collector相关的知识,希望对你有一定的参考价值。

 

题目描述

Bessie the cow, always a fan of shiny objects, has taken up a hobby of mining diamonds in her spare time! She has collected 技术分享 diamonds (技术分享) 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 技术分享 (two diamonds can be displayed together in the same case if their sizes differ by exactly 技术分享). Given 技术分享, 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 技术分享 and 技术分享 (技术分享).

The next 技术分享 lines each contain an integer giving the size of one of the

diamonds. All sizes will be positive and will not exceed 技术分享.

 

输出格式:

 

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

 

从左往右,从右往左各扫一遍,记录从某个点开始最多能取的数量。

然后枚举中点往左右取,记录最大值。

 1 /*by SilverN*/
 2 #include<iostream>
 3 #include<algorithm>
 4 #include<cstring>
 5 #include<cstdio>
 6 #include<cmath>
 7 using namespace std;
 8 const int mxn=51000;
 9 int read(){
10     int x=0,f=1;char ch=getchar();
11     while(ch<0 || ch>9){if(ch==-)f=-1;ch=getchar();}
12     while(ch>=0 && ch<=9){x=x*10+ch-0;ch=getchar();}
13     return x*f;
14 }
15 int a[mxn];
16 int n,k;
17 int w[mxn],r[mxn];
18 int main(){
19     n=read();k=read();
20     int i,j;
21     for(i=1;i<=n;i++){
22         a[i]=read();
23     }
24     sort(a+1,a+n+1);
25     int hd=1;
26     for(i=1;i<=n;i++){
27         while(a[i]-a[hd]>k)hd++;
28         w[i]=max(w[i-1],i-hd+1);
29     }
30     hd=n;
31     for(i=n;i;i--){
32         while(a[hd]-a[i]>k)hd--;
33         r[i]=max(r[i+1],hd-i+1);
34     }
35     int ans=0;
36     for(i=1;i<n;i++){
37         ans=max(ans,w[i]+r[i+1]);
38     }
39     printf("%d\n",ans);
40     return 0;
41 }

 

以上是关于洛谷P3143 [USACO16OPEN]钻石收藏家Diamond Collector的主要内容,如果未能解决你的问题,请参考以下文章

P3143 [USACO16OPEN]钻石收藏家Diamond Collector(伸缩法)

P3143 [USACO16OPEN]钻石收藏家Diamond Collector[two-pointers]

Luogu P3143 [USACO16OPEN]钻石收藏家Diamond Collector 题解

洛谷 P3147 [USACO16OPEN]262144

洛谷 P3146 [USACO16OPEN]248

洛谷P3146 [USACO16OPEN]248