二分模板// The Frog's Games +Aggressive cows


二分的情况不同所输出的模板也不同列如下面两个题目

The Frog's Games

代码如下

//二分专练
#include <stdio.h> //lower_bound大于等于它的第一个数
#include <iostream> //upper_bound大于 它的第一个数
#include <algorithm>
#include <string.h>
using namespace std;
int a[500005];
int n,m;//l河长,n块石头位子,可以跳m次
bool lpt(int wf)
{
int pos=0;
for(int x=1;x<=m;x++)
{
pos=upper_bound(a,a+n,a[pos]+wf)-a-1;
if(pos>=n-1)
return true;
}
return false;
}
int main()
{
int l,i,j,left,right,mid;
while(scanf("%d%d%d",&l,&n,&m)!=EOF)
{
int minn=1e9;
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
sort(a,a+n+1);
a[0]=0;a[n+1]=l;
n=n+2;
right=l;
left=l/m;
while(left<=right)
{
mid=(left+right)/2;
if(lpt(mid))
{
right=mid-1;
minn=min(minn,mid);
}
else
left=mid+1;
}
printf("%d\n",minn);
}
return 0;

}
Aggressive cows

代码如下

//二分专练
#include <stdio.h> //lower_bound大于等于它的第一个数
#include <iostream> //upper_bound大于 它的第一个数
#include <algorithm>
#include <string.h>
using namespace std;
int a[100005];
int n,c;
bool lpt(int x)
{
int d,j,ans=0; d=a[0];
for(j=1;j<=n-1;j++)
{
if(a[j]-d>=x)
{
ans++;
d=a[j];
}
}
if(ans<c-1) return true;
else return false;
}
int main()
{
int maxm=0,i,m,mid,left,right;
scanf("%d%d",&n,&c);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,a+n);//1 2 4 8 9
left=0;
right=(a[n-1]-a[0])/(c-1);//4
while(left<=right)
{
mid=(left+right)/2;
if(lpt(mid))
{
right=mid-1;
}
else
{
left=mid+1;
maxm=max(maxm,mid);
}
}
printf("%d\n",maxm);
return 0;
}

c语言代码~ 初学者一起来学、、

优质内容筛选与推荐>>
1、nohup 详解
2、我是如何学习写一个操作系统(五):故事的高潮之进程和线程1
3、前端html
4、CSS选择器
5、base标签的应用


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号