算法与数据结构---二分法

二分法

— 实数二分模板

在这里插入图片描述

小数二分模板

在这里插入图片描述

[USACO07MAR] Monthly Expense S

题目描述

Farmer John is an astounding accounting wizard and has realized he might run out of money to run the farm. He has already calculated and recorded the exact amount of money (1 ≤ moneyi ≤ 10,000) that he will need to spend each day over the next N (1 ≤ N ≤ 100,000) days.

FJ wants to create a budget for a sequential set of exactly M (1 ≤ M ≤ N) fiscal periods called “fajomonths”. Each of these fajomonths contains a set of 1 or more consecutive days. Every day is contained in exactly one fajomonth.

FJ’s goal is to arrange the fajomonths so as to minimize the expenses of the fajomonth with the highest spending and thus determine his monthly spending limit.

给出农夫在n天中每天的花费,要求把这n天分作m组,每组的天数必然是连续的,要求分得各组的花费之和应该尽可能地小,最后输出各组花费之和中的最大值

输入格式

Line 1: Two space-separated integers: N and M

Lines 2…N+1: Line i+1 contains the number of dollars Farmer John spends on the ith day

输出格式

Line 1: The smallest possible monthly limit Farmer John can afford to live with.

样例 #1

样例输入 #1

7 5
100
400
300
100
500
101
400

样例输出 #1

500

提示

If Farmer John schedules the months so that the first two days are a month, the third and fourth are a month, and the last three are their own months, he spends at most $500 in any month. Any other method of scheduling gives a larger minimum monthly limit.

分析

问n个数分成m段,并且每段的和的最大值最小

最大值最小,最小值最大……暴露出这题是二分答案,这也是做题时的一个小技巧,快速分辨出这题用什么方法
手动模拟出样例如何求出500
根据样例可得,7个数要分成五段,并且每段连续

左边界取7个元素中最大的一个,也就是500;(如果不是最大的一个数,根本不能分)

右边界为7个元素之和,也就是1901(最大7个数合成一段)

100400300100500101400

此时mid为(Left+Right)/2,也就是1200(向下取整)

这时,判断每段和为1200是否合法

  1. 100+400+300+100=900
  2. 500+101+400=1001

只分成了两段,不合法,为了分的段数更多,需要将每段和缩小,也就是调整左边界,此时 Right为 mid−1,1199

继续分,(1999+500)/2=849
mid=(1999+500)/2=849(任然向下取整)

  1. 100+400+300=800
  2. 100+500+101=701
  3. 400

三段,不合法,继续分

Right=mid−1=849−1=848
mid=(500+848)/2=67

  1. 100+400=500
  2. 300+100=400
  3. 500
  4. 101+400=501

四段,继续

Right=mid−1=674−1=673
mid=(500+673)/2=586

  1. 100+400=500
  2. 300+100=400
  3. 500
  4. 101+400=501

四段,继续

Right=mid−1=586−1=585
mid=(500+585)/2=542

  1. 100+400=500
  2. 300+100=400
  3. 500
  4. 101+400=501

……………

直到——

Right=500,
Left=500

100+400=500
2. 300+100=400
3. 500
4. 101
5. 400

这时,正好分为五段,并且每段最大值最小

代码

#include<iostream>
#include<algorithm>
using namespace std;
int n, m, a[100010], low = 0, high = 0, mid;
int judge(int mid)
{
	int sum = 0, ans = 1;//开始为整体为一组,//sum是累加当前的钱,cnt是要分成几组
	for (int i = 1; i <= n; i++)
	{
		if (sum + a[i] <= mid)//如果加上这个月的花费还比枚举到的开销小
			sum += a[i];//那就继续加
		else
		{
			sum = a[i];//不然就要分一组出来
			ans++;
		}
	}
	if (ans > m)
		return 1;//组数偏多mid偏小 low=mid+1
	else
		return 0;//组数偏少mid偏大
}
int main()
{
	cin >> n >> m;
	for (int i = 1; i <= n; i++)
	{
		cin >> a[i];
		low = max(a[i], low);//预处理,最小开销至少跟花费最大的那个月一样
		high += a[i];//最大开销可能是所有的月加起来
	}
	while (low <= high)
	{
		mid = low + (high - low) / 2;
		if (judge(mid))//
			low = mid + 1;
		else
			high = mid - 1;
			
	}
	cout << low << endl;
	return 0;
}

# [USACO06DEC] River Hopscotch S

题目描述

Every year the cows hold an event featuring a peculiar version of hopscotch that involves carefully jumping from rock to rock in a river. The excitement takes place on a long, straight river with a rock at the start and another rock at the end, L units away from the start (1 ≤ L ≤ 1,000,000,000). Along the river between the starting and ending rocks, N (0 ≤ N ≤ 50,000) more rocks appear, each at an integral distance Di from the start (0 < Di < L).

To play the game, each cow in turn starts at the starting rock and tries to reach the finish at the ending rock, jumping only from rock to rock. Of course, less agile cows never make it to the final rock, ending up instead in the river.

Farmer John is proud of his cows and watches this event each year. But as time goes by, he tires of watching the timid cows of the other farmers limp across the short distances between rocks placed too closely together. He plans to remove several rocks in order to increase the shortest distance a cow will have to jump to reach the end. He knows he cannot remove the starting and ending rocks, but he calculates that he has enough resources to remove up to M rocks (0 ≤ M ≤ N).

FJ wants to know exactly how much he can increase the shortest distance *before* he starts removing the rocks. Help Farmer John determine the greatest possible shortest distance a cow has to jump after removing the optimal set of M rocks.

奶牛跳房子:从N块石头中移除M块,使得间距最小值最大。

输入格式

Line 1: Three space-separated integers: L, N, and M

Lines 2…N+1: Each line contains a single integer indicating how far some rock is away from the starting rock. No two rocks share the same position.

输出格式

Line 1: A single integer that is the maximum of the shortest distance a cow has to jump after removing M rocks

样例 #1

样例输入 #1

25 5 2
2
14
11
21
17

样例输出 #1

4

提示

Before removing any rocks, the shortest jump was a jump of 2 from 0 (the start) to 2. After removing the rocks at 2 and 14, the shortest required jump is a jump of 4 (from 17 to 21 or from 21 to 25).

分析

1、 由于n是中间的石头数,并未包含终点的石头,所以要加入到距离队列中。题目的意思很简单,就是最多移走m块石头,使得选手跳跃的最短距离最大即可。
2. 由于二分的数组需要有序,所以需要用sort排好。
3. 二分距离,因为答案在二分的左侧(较小数中的最大值),所以需要及时记录答案(即mid)。
4.**判断函数:**统计出当距离为s时总共需要移走几个石头。具体思路用到贪心,详见注释。有两种写法:一个是直接统计出需要移走的数量,一个是先统计留下来的石头的总数,再在return时用总数来算出移走的数量。
5. 简单的思路:从起点出发,先选定一段距离mid,若前面的石头B与你所站着的石头A的距离小于mid,就把B搬掉,记录一下;如果不,就把B留下,再跳到石头B上。照这个步骤多次循环后,如果搬掉的石头多了,就把距离mid定小点;如果少了,就把mid定大点。

代码

#include<iostream>
#include<algorithm>
using namespace std;


int t,m,n,r=0,l;
int a[50005];
bool check(int mid){
	int b = 0,j = 0;//b是搬走的石头数,j为第i个石头的上一块石头 
	for(int i=1;i<=n+1;i++){
		if(a[i]-a[j]<mid){//两个石头之间的距离小于中间值 
			b++;//石块数++
		}
		else
		j=i;//下一块石头的上一块是他
	}
	return b<=m;//判断有没有大于规定
}
int main()
{
	cin>>t>>n>>m;
	for(int i=1;i<=n;i++){
		cin>>a[i];
	}
	sort(a,a+n+1);//排序,排序,排序!!! 
	r=t+1;//规定边界,让以后不用特判终点的石头的情况 
	a[n+1]=t;//这样方便终点的石头调用
	while(l + 1 < r){
		int mid=l+(r-l)/2;
		if(check(mid)){
			l = mid;//还可以继续放石头
		}
		else
		r=mid;//少几块石头
	}
	cout<< l<<endl;
	return 0;
}

# 进击的奶牛

题目描述

Farmer John 建造了一个有 N N N 2 ≤ N ≤ 1 0 5 2 \leq N \leq 10 ^ 5 2N105) 个隔间的牛棚,这些隔间分布在一条直线上,坐标是 x 1 , x 2 , ⋯   , x N x _ 1, x _ 2, \cdots, x _ N x1,x2,,xN 0 ≤ x i ≤ 1 0 9 0 \leq x _ i \leq 10 ^ 9 0xi109)。

他的 C C C 2 ≤ C ≤ N 2 \leq C \leq N 2CN)头牛不满于隔间的位置分布,它们为牛棚里其他的牛的存在而愤怒。为了防止牛之间的互相打斗,Farmer John 想把这些牛安置在指定的隔间,所有牛中相邻两头的最近距离越大越好。那么,这个最大的最近距离是多少呢?

输入格式

1 1 1 行:两个用空格隔开的数字 N N N C C C

2 ∼ N + 1 2 \sim N+1 2N+1 行:每行一个整数,表示每个隔间的坐标。

输出格式

输出只有一行,即相邻两头牛最大的最近距离。

样例 #1

样例输入 #1

5 3
1
2
8
4
9

样例输出 #1

3

分析

本文主要分析二分答案过程中,对于上下界的理解和实现。

我写二分答案时,上下界没有写好导致Wrong Answer。又看到讨论区有人的上下界写错了,于是TLE。所以决定仔细分析一下二分的上下界问题。

众所周知,二分答案时,需要有上界、下界、中点。分别命名为left,right,mid。

此题中,要求最大值,因此有重要结论:若mid为解,则最优解一定属于[mid, right]。若mid不为解,则最优解一定属于[right, mid)。对这部分不清楚的可以阅读这里,一篇很清晰地讲述二分答案的题解。

代码

#include<iostream>
#include<algorithm>
using namespace std;
int t,m,n,r=0,l,mid,ans;
int a[100005];
bool check(int mid){
	int b = 1 ,j = 0;
	for(int i=1;i<n;i++){
		if(a[i]-a[j]>=mid){//两个棚之间的距离比最大距离mid还要大,此时可以再放进去一头牛
			b++;
			j=i;//更新j的坐标
		}		
	}
	return b>=m;
}
int main()
{
	cin>>n>>m;
	for(int i=0;i<n;i++){
		cin>>a[i];
	}
	sort(a,a+n);//排序,排序,排序!!! 
	r=a[n-1]-a[0]; //棚的总长度

	while(l <= r){
	     mid=l+(r-l)/2;
		if(check(mid)){
			l = mid + 1;
		}
		else
		r=mid-1;
	}
	cout<< r <<endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值