Aggressive cows POJ 2456(二分)

原题

题目链接

题目分析

题目要求最大最小值,可以考虑二分,C(d)为任意两头牛的距离不小于d.判断方法如下,先按牛舍的x值从小到大排序,然后把第一头牛放在x0,从x1开始遍历,当xn-x0>=d时,则放下第二头牛,以此类推.如果能放下C头牛,则继续二分右区间,否则二分左区间.

代码

 1 #include <cstdio>
 2 #include <cstdlib>
 3 #include <iostream>
 4 #include <algorithm>
 5 #include <utility>
 6 #include <ctime>
 7 #include <cmath>
 8 #include <cstring>
 9 #include <string>
10 #include <stack>
11 #include <queue>
12 #include <vector>
13 #include <set>
14 #include <map>
15 
16 using namespace std;
17 typedef unsigned long long ULL;
18 typedef long long LL;
19 typedef long double LB;
20 const int INF_INT=0x3f3f3f3f;
21 const LL INF_LL=0x3f3f3f3f3f3f3f3f;
22 
23 int N,C;
24 int num[100000];
25 
26 bool check(int d)
27 {
28     int k=1,last=0,n=1;
29     while(n<N)
30     {
31         if(num[n]-num[last]>=d) k++,last=n;
32         n++;
33     }
34     if(k<C) return false;
35     else return true;
36 }
37 
38 int main()
39 {
40 //    freopen("testdata.in","r",stdin);
41 //  freopen("std.out","w",stdout);
42     cin>>N>>C;
43     for(int i=0;i<N;i++)
44         scanf("%d",&num[i]);
45     sort(num,num+N);
46     int l=1,r=INF_INT;
47     while(r-l>1)
48     {
49         int mid=(l+r)/2;
50         if(check(mid)) l=mid;
51         else r=mid;
52     }
53     printf("%d\n",l);
54     return 0;
55 }

猜你喜欢

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