Diamond Collector

链接:https://ac.nowcoder.com/acm/contest/6185/A
来源:牛客网
 

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld

题目描述

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≤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.

输入描述:

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

示例1

输入

7 3
10
5
1
12
9
5
14

输出

5

思路:排序,对每个位置求此位置之前的k长度区间和之后的k长度区间,求和的最大值。

做法一:遍历。复杂度是o(n^2),但也能过,可能数据太水了。

#include<iostream>
#include<set>
#include<algorithm>

using namespace std;

const int N = 50050;

int num[N];
int r[N];
int ans;

int main()
{
	int n,k;
	cin>>n>>k;
	for(int i=1; i<=n; i++) scanf("%d",&num[i]);
	sort(num+1, num+n+1);
	int maxn = 0;//第一个架子能摆的最多钻石数 
	for(int i=1; i<=n; i++)
	{
		int j = i;
		while(num[j] <= num[i] + k && j <= n) j++;
		r[j] = max(j-i, r[j]);//j左边符合条件长度 	
		maxn = max(maxn, r[i]);	 
		ans = max(j-i+maxn, ans); 
		
	}
	cout<<ans;
	return 0;
} 

做法二:用二分代替上面做法的循环找合适位置。

#include<iostream>
#include<set>
#include<algorithm>

using namespace std;

const int N = 50050;

int num[N];
int c[N];
int ans;

int main()
{
	int n,k;
	cin>>n>>k;
	for(int i=1; i<=n; i++) scanf("%d",&num[i]);
	sort(num+1, num+n+1);
	int maxn = 0;//第一个架子能摆的最多钻石数 
	for(int i=1; i<=n; i++)
	{
		int l = i,r = n+1;
		while(l < r)
		{
			int mid = (l + r) >> 1;
			if(num[mid] > num[i] + k) r = mid;
			else l = mid + 1; 
		}
		c[r] = max(r-i, c[r]);//j左边符合条件长度 	
		maxn = max(maxn, c[i]);	 
		ans = max(r-i+maxn, ans); 		
	}
	cout<<ans;
	return 0;
} 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值