二分贪心练习--E(牛的距离)
来源:互联网 发布:网易养猪场 知乎 编辑:程序博客网 时间:2024/05/22 09:46
题目描述:
Description
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?
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
* Lines 2..N+1: Line i+1 contains an integer stall location, xi
Output
* Line 1: One integer: the largest minimum distance
Sample Input
5 312849
Sample Output
3
Hint
OUTPUT DETAILS:
FJ can put his 3 cows in the stalls at positions 1, 4 and 8, resulting in a minimum distance of 3.
Huge input data,scanf is recommended.
FJ can put his 3 cows in the stalls at positions 1, 4 and 8, resulting in a minimum distance of 3.
Huge input data,scanf is recommended.
解题思路:
经典的二分算法。首先将每一个摊位的位置进行排序(stable_sort),然后用二分法求该最值。
源代码:
#include <iostream>#include <stdio.h>#include <algorithm>#include <cstring>using namespace std;int length[100005];int main(){ int N,C,i; int max=0,mid; int lp,rp; scanf("%d",&N); scanf("%d",&C); length[0]=0; for (i=1;i<=N;i++) scanf("%d" , &length[i]); stable_sort(length,length+N+1);//对摊位的位置进行排序 lp=length[1]; //二分法,lp为最小值,rp为最大值。 rp=length[N]; while (lp<rp) { int cnt=1; //一头牛放在第一个位置 int j=1; mid=(lp+rp)/2; for (i=2;i<=N;i++) { if (length[i]-length[j]>=mid) //如果第i个位置减去第j个位置≥mid,可放置牛,然后从该位置再往后找 { cnt++; j=i; } } if (cnt>=C) //如果mid的距离能放的牛数cnt≥给定的牛的数目,用max存该最值。 { if (max<mid) max=mid; lp=mid+1; //下界变为中间值 } else rp=mid; } printf("%d\n",max);}
0 0
- 二分贪心练习--E(牛的距离)
- 二分贪心 E 找距离最大的最小值
- 二分贪心专题E
- 二分贪心 E
- 二分贪心 E
- 二分贪心 E题
- 二分贪心—E
- 二分贪心-E
- 二分贪心e
- ACM-二分贪心E-05
- 二分贪心——E
- 2016春季练习——二分+贪心
- 二分贪心练习--G(烧绳子问题)
- “师创杯”山东理工大学第九届ACM程序设计竞赛 热身赛 E.上色的纱雾【二分+贪心】
- 二分贪心练习--T(用最少的箱子放所有的货物)
- Codeforces #227(Div2) E. George and Cards 贪心+二分
- Codeforces 807E Prairie Partition 贪心思维+二分
- nyoj914Yougth的最大化【二分+贪心】
- vue实现webapp
- 设计模式-构建者模式
- 二叉树前序,中序,后序遍历详解
- linux与window文件共享——Samba配置详细过程
- office
- 二分贪心练习--E(牛的距离)
- 第四 管理系统中的简单分区和文件系统
- spring-batch很不错的资料
- TensorFlow-BatchNormalization
- context:component-scan标签的use-default-filters属性的作用以及原理
- 一些社交软件介绍
- 数据库的增删改查案例
- C语言实现应用程序开机自启动(写进注册表)
- Android Calendar Provider(日历事件)