Aggressive cows 愤怒的牛 HYSBZ - 1734(题解)

原题

https://www.lydsy.com/JudgeOnline/problem.php?id=1734

题目大意

题意是讲有n个隔间,隔间范围在[0,1 000 000 000],然后有c头牛,要把c头牛放进这些隔间里并使他们两两间的距离最大,求这个最大距离.(同一个隔间只能放1头牛)

题目分析

二分模板题,用二分法直接查找答案,也就是查找两头牛之间的最大距离(初始区间设为[1,1000000001))(左闭右开).当二分到某个距离假设为n时,只需要检查把牛按最小距离为n从头开始放牛(隔间的数据记得排序),遍历一遍看看牛放不放得下即可.如果牛放得下,说明可以n就是答案或者答案在n的右边,可以把区间左边界换成n,如果放不下则把区间右边界换成n.(这里注意当二分区间类似[1,2)就可以终止了,答案是1)

代码

 1 #include <cstdio>
 2 #include <cmath>
 3 #include <iostream>
 4 #include <cstring>
 5 #include <algorithm>
 6 #include <vector>
 7 #include <string>
 8 #include <utility>
 9 #include <queue>
10 #include <stack>
11 const int INF=0x3f3f3f3f;
12 using namespace std;
13 
14 long a[100000];
15 
16 
17 bool judge(long x,long n,long c) //c是所要放牛的数量,x是距离,n是隔间数量 
18 {
19     for(int i=0,j=0;i<n;i++)
20     {
21         if(!c) break;
22         if(i==0) c--;
23         else
24         {
25             if(a[i]-a[j]>=x) c--,j=i;
26         }
27     }
28     if(!c) return true;
29     else return false;
30 }
31 
32 int main()
33 {
34     long n,c;
35     cin>>n>>c;
36     for(long i=0;i<n;i++)
37     cin>>a[i];
38     sort(a,a+n);
39     long ans,r=1e9+1,l=1;
40     while(r-l>1)
41     {
42         long mid=(l+r)/2;
43         if(judge(mid,n,c)) l=mid;
44         else r=mid;
45     } 
46 
47     cout<<l<<endl;
48     return 0;
49 }

猜你喜欢

转载自www.cnblogs.com/VBEL/p/10427674.html
今日推荐