蓝桥杯—跳石头—二分答案

1、问题描述

题目描述

这项比赛将在一条笔直的河道中进行,河道中分布着一些巨大岩石。组委会已经选择好了两块岩石作为比赛起点和终点。在起点和终点之间,有 N 块岩石(不含起点和终点的岩石)。在比赛过程中,选手们将从起点出发,每一步跳向相邻的岩石,直至到达终点。

为了提高比赛难度,组委会计划移走一些岩石,使得选手们在比赛过程中的最短跳跃距离尽可能长。由于预算限制,组委会至多从起点和终点之间移走 M 块岩石(不能移走起点和终点的岩石)。

输入格式

第一行包含三个整数 L,N,M,分别表示起点到终点的距离,起点和终点之间的岩石数,以及组委会至多移走的岩石数。保证 L >= 1且 N >= M >= 0。

接下来 N 行,每行一个整数,第 i 行的整数 D( 0 < D< L), 表示第 i 块岩石与起点的距离。这些岩石按与起点距离从小到大的顺序给出,且不会有两个岩石出现在同一个位置。

输出格式

一个整数,即最短跳跃距离的最大值。

输入输出样例

输入 

25 5 2 
2
11
14
17 
21

输出 

4

说明/提示

输入输出样例 1 说明:将与起点距离为 2和 14 的两个岩石移走后,最短的跳跃距离为 4(从与起点距离 17 的岩石跳到距离 21 的岩石,或者从距离 21 的岩石跳到终点)。

2、代码实现

import java.util.Scanner;

public class 跳石头 {
	static int end;
	static int stone;
	static int delete;
	static int[] distance;
	
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		end = scanner.nextInt();
		stone = scanner.nextInt();
		delete = scanner.nextInt();
		distance = new int[stone + 2];
		int max = 0;
		for(int i = 1;i <= stone;i++) {
			distance[i] = scanner.nextInt();
			max = Math.max(max, distance[i]);
		}
		distance[0] = 0;
		distance[stone + 1] = end;
		
		if(stone == 0) {
			System.out.println(end);
			return;
		}
		//最小距离最大
		int left = 1;
		int right = max;
		int middle = 0;
		while(left < right) {
			middle = (left + right + 1) >> 1;
			if(check(middle)) {
				left = middle;
			}else {
				right = middle - 1;
			}
		}
		System.out.println(left);
	}
	public static boolean check(int middle) {
		int start = 0;
		int current = 0;
		int count = 0;
		while(current < stone + 1) {
			current++;
			//当前间距不能得到满足,将当前位置的石头删掉
			if(distance[current] - distance[start] < middle) {
				//需要删除的个数
				count++;
			}else {
				start = current;
			}
		}
		return count <= delete;
	}
}

 

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@小红花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值