二分:
使用二分必须保证数列是有序递增数列,下边是实现代码
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