本周算法题总结:二分

二分:

使用二分必须保证数列是有序递增数列,下边是实现代码

int up_down( int *num,  int l, int r, int key )
{
   
    int mid;

    while ( l < r ) {
          //有些人也会写l<=r,但有个小胖子要我这么写
        mid = l+(r-l)/2;		//相当于(l+r)/2,还是那个小胖子非要我这么写......
        if ( num[mid] >= key )
            r = mid;
        else
            l = mid+1;	     //这样l就是所求key的最左边的下标
    }
    return l;
}

下面是一些例题

Turn It Off

Time Limit: 1 Second Memory Limit: 65536 KB
It’s already 21:30 now, and it’s time for BaoBao to go to bed. To ensure his sleeping quality, BaoBao decides to turn all the lights in his bedroom off.

There are lights, numbered from 1 to , arranged in a row in BaoBao’s bedroom. Each time BaoBao can select an integer and turn all the lights numbered from to (both inclusive) off, where is a predefined positive integer. Note that each time the value of must be the same.

Given the initial status of all the lights, please help BaoBao determine the smallest possible so that he can turn all the lights off within times.

Input
There are multiple test cases. The first line of the input contains an integer , indicating the number of test cases. For each test case:

The first line contains two integers n and k ().

The second line contains a string (, ) indicating the initial status of the lights. Let be the -th character in , if then the -th light is initially on, otherwise it’s initially off. It’s guaranteed that there is at least one ‘1’ in .

It’s guaranteed that the sum of of all test cases will not exceed .

Output
For each test case output one line containing one integer, indicating the smallest possible .

Sample Input
2
10 4
0101011111
3 1
010
Sample Output
3
1

题目思路:用二分的方法,让left=1,right=总灯数,key为每次熄灭的灯数,用n来记录总次数,只要n小于等于k即可,最后输出最小的key,也就是left。
#include <stdio.h>
#include <string.h>

char a[200100];

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值