【2020.10.27SSL模拟赛普及T2】小biu放牛【二分】【贪心】

在这里插入图片描述
在这里插入图片描述

分析

这题二分 贪心 来考虑放牛
通过输入计算牛的head ,tail 再判断越界情况即可

上代码

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

int n,x,m,a[1000001];

bool check(int p)
{
    
    
	int head=0,tail=0;
	for(int i=1;i<=n;i++)
	{
    
    
		head=max(tail,a[i]-x-p);  //计算head位置
		if(abs(head-a[i]+x)>p) return 0;  //判越界
		tail=head+2*x; //计算tail
		if(tail>m) return 0;  //判越界
	}
	return true;
}

int main()
{
    
    
	cin>>n>>x>>m;
	for(int i=1;i<=n;i++)
	{
    
    
		cin>>a[i];
	}
	int l=0,r=m;
	while(l<=r)
	{
    
    
		int mid=(l+r)/2;
		if(check(mid)) r=mid-1;
		else l=mid+1;
	}
	if(l==(m+1)) cout<<-1;
	else cout<<l;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/dglyr/article/details/109343135