最大化最小值----》POJ2456

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40984919/article/details/81304507

C(d):可以安排牛的位置使得最近的两头牛的距离不小于d(进行搜索)

 #include<set>
#include<map>
#include<stack>
#include<bitset>
#include<math.h>
#include<string>
#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define pi acos(-1)
#define close ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
using namespace std;
typedef long long ll;
const int MAX_N=1000000+50;
const int INF=0x3f3f3f3f;
ll mod = 1e9+7;

int N,M;
int x[MAX_N];

bool C(int d){
	int last = 0;
	for(int i = 1; i < M; i++){
		int crt = last + 1;
		while(crt < N && x[crt] - x[last] < d){
			crt++;
		}
		if(crt == N) return false;
		last = crt;
	}
	return true;
}

void solve(){
	//最开始的时候对x进行排序 
	sort(x,x + N);
	
	//初始化解的存在范围
	int lb = 0, ub = INF;
	while(ub - lb > 1){
		int mid = (lb + ub) / 2;
		if(C(mid)) lb = mid;
		else ub = mid;
	}
	printf("%d   %d\n",lb,ub);  
	//输出ub的原因是对比一下  为什么最后输出lb而不输出rb 
	//显而易见,每一次找到那个最小的即退出(满足条件) 
}

int main(){
	scanf("%d%d",&N,&M);
	for(int i = 0; i < N; i++){
		scanf("%d",&x[i]);
	}
	solve();
 	return 0;
}

/*
                ********
               ************
               ####....#.
             #..###.....##....
             ###.......######              ###            ###
                ...........               #...#          #...#
               ##*#######                 #.#.#          #.#.#
            ####*******######             #.#.#          #.#.#
           ...#***.****.*###....          #...#          #...#
           ....**********##.....           ###            ###
           ....****    *****....
             ####        ####
           ######        ######
##############################################################
#...#......#.##...#......#.##...#......#.##------------------#
###########################################------------------#
#..#....#....##..#....#....##..#....#....#####################
##########################################    #----------#
#.....#......##.....#......##.....#......#    #----------#
##########################################    #----------#
#.#..#....#..##.#..#....#..##.#..#....#..#    #----------#
##########################################    ############
*/

猜你喜欢

转载自blog.csdn.net/qq_40984919/article/details/81304507