洛谷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;
}