题目:洛谷1316 丢瓶盖、POJ Aggressive cows(二分)

洛谷1316 丢瓶盖
题目描述
陶陶是个贪玩的孩子,他在地上丢了A个瓶盖,为了简化问题,我们可以当作这A个瓶盖丢在一条直线上,现在他想从这些瓶盖里找出B个,使得距离最近的2个距离最大,他想知道,最大可以到多少呢?

输入输出格式
输入格式:
第一行,两个整数,A,B。(B<=A<=100000)
第二行,A个整数,分别为这A个瓶盖坐标。

输出格式:
仅一个整数,为所求答案。

思路
最小值的最大化,(或者是最大值的最小化)用二分。从小到大排序好后,a[n]-a[1]的值为最长线段的长度,最短设为1,然后进行二分,找到一个最大的满足两个点之间的距离为大于等于这个值的个数最少要符合c个。因为这里l=mid+1,所以最后要输出l-1。

代码

#include <bits/stdc++.h>
using namespace std;
int n, c, a[100005], l=1, r, mid;
bool judge(int x)
{
	int tot=1, t=1;
	for (int i=2; i<=n; i++){
		if (a[i]-a[t]>=x){
			tot++;
			t=i;
		}
	}
	if (tot>=c)	return true;
	else	return false;
}
void func()
{
	r=a[n]-a[1];
	while (l<=r){
		mid=(l+r)/2;
		if (judge(mid))
			l=mid+1;
		else
			r=mid-1;
	}
}
int main()
{
	cin>>n>>c;
	for (int i=1; i<=n; i++)
		cin>>a[i];
	sort(a+1, a+n+1);
	func();
	cout<<l-1;
	return 0;
}

POJ Aggressive cows
题目描述
Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a straight line at positions x1,…,xN (0 <= xi <= 1,000,000,000).

His C (2 <= C <= N) cows don’t like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ want to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?
Input

  • Line 1: Two space-separated integers: N and C

  • Lines 2…N+1: Line i+1 contains an integer stall location, xi

Output

  • Line 1: One integer: the largest minimum distance
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
using namespace std;
int a[100005], n, c; 
int judge(int x)
{
	int sum=0, t=1;
	for (int i=2; i<=n; i++){
		if (a[i]-a[t]>=x){
			sum++;
			t=i;
		}
	} 
	if (sum>=c-1)	return 1;
	else	return 0;
}
int main()
{
	
	scanf("%d%d", &n, &c);
	for (int i=1; i<=n; i++)
		scanf("%d", &a[i]);
	sort(a+1, a+n+1);
	int l=1, r=a[n]-a[1], ans, mid;
	while (l<=r){
		mid=(l+r)/2;
		if (judge(mid)){
			l=mid+1;
			ans=mid;
		}else
			r=mid-1;
	}
	printf("%d", ans);
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

H4ppyD0g

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值