洛谷 P3143 [USACO16OPEN]钻石收藏家Diamond Collector 解题报告

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 \(N\) diamonds (\(N \leq 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 \(K\) (two diamonds can be displayed together in the same case if their sizes differ by exactly \(K\)). Given \(K\), please help Bessie determine the maximum number of diamonds she can display in both cases together.

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

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

输入输出格式

输入格式:

The first line of the input file contains \(N\) and \(K\) (\(0 \leq K \leq 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,000\).

输出格式:

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

Bessie can showcase in total in both the cases.


方法很多而且都很神奇

我的做法是:对点排序,枚举每个点作为左端点,二分一个区间的左端点超过它的右端点的位置。

在这个位置的右边选择一个最大的,在这个位置左边选择最大的,都可以事先维护(把区间重复和不重复分开统计)

注意预处理时也需要一些二分


Code:

#include <cstdio>
#include <algorithm>
const int N=5e4+10;
const int inf=0x3f3f3f3f;
int max(int x,int y){return x>y?x:y;}
int n,k,a[N],cntl[N],cntr[N],cntf[N],fr[N],fr2[N];
std::pair <int,int > b[N];
int main()
{
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
b[i].second=a[i];
b[i].first=b[i].second-k;
}
std::sort(a+1,a+1+n);//原来的
std::sort(b+1,b+1+n);//充当右端点后以左端点为关键字
for(int i=1;i<=n;i++)//这个自己充当右端点可以覆盖左边的几个(不考虑左端点)?
cntf[i]=fr[i]=i;
for(int i=1;i<=n;i++)//自己充当左端点右边覆盖几个?
{
if(a[n]<=b[i].second+k) cntl[i]=n-cntf[i]+1;
else cntl[i]=std::upper_bound(a+1,a+1+n,b[i].second+k)-a-1-cntf[i]+1;
}
for(int i=n;i;i--)//这个自己充当右端点可以覆盖左边的几个(考虑左端点)?
{
if(a[1]>=b[i].second-k) cntr[i]=cntf[i];
else cntr[i]=cntf[i]-(std::lower_bound(a+1,a+1+n,b[i].second-k)-a-1);
fr2[i]=max(fr2[i+1],cntr[i]);
}
int ans=0;
for(int i=1;i<=n;i++)//枚举自己当左端点的点
{
if(b[i].second+k>b[n].first)
{
ans=max(ans,fr[n]-cntf[i]+1);
}
else
{
std::pair <int,int> d=std::make_pair(b[i].second+k,inf);
int pos=std::upper_bound(b+1,b+1+n,d)-b;
ans=max(ans,cntl[i]+fr2[pos]);
ans=max(ans,fr[pos]-cntf[i]+1);
}
}
printf("%d\n",ans);
return 0;
}

2018.8.30

上一篇:Android EditText获取焦点和失去焦点监听事件


下一篇:Bzoj 4582 [Usaco2016 Open] Diamond Collector 题解