您的位置:首页 > 其它

二分查找之变形

2011-10-31 15:14 483 查看
//寻找一个数,找到刚好比他小的数。

比如-1 1 1 1 2 ~~~

如果要找1,那么返回的是-1的位置0。

如果1开头,那么返回位置-1.

int lbs(int *a, int n, int v){
int b = 0, e = n, m;
while (b < e){
m = b + ((e - b) >> 1);
if (a[m] >= v) e = m;
else b = m + 1;
}
while (0 <= m && a[m] >= v) --m;
return m;
}


用同样的方法来找刚好比其大的数。

int rbs(int *a, int n, int v){
int b = 0, e = n, m;
while (b < e){
m = b + ((e - b) >> 1);
if (a[m] <= v) b = m + 1;
else e = m;
}
while (m < n && a[m] <= v) ++m;
return m;
}


这两个函数可以用于对在[b , e]区间里面的数进行计数。比如POJ 2413题。不过要注意数列是从 1, 2, 3开始的。不是一般的从1 1 2 3开始。

粘个java的代码。

import java.io.*;
import java.util.*;
import java.math.*;

public class Main {
public static int leftBinarySearch(BigInteger [] w, int n, BigInteger v){
int b = 0, e = n, m = 0, re;
while (b < e){
m = (b + e) >> 1;
re = w[m].compareTo(v);
if (re >= 0) e = m;
else b = m + 1;
}
while (0 <= m && w[m].compareTo(v) >= 0) --m;
return m;
}

public static int rightBinarySearch(BigInteger [] w, int ms, BigInteger v){
int b = 0, e = ms, m = 0, re;
while (b < e){
m = b + ((e - b) >> 1);
re = w[m].compareTo(v);
if (re <= 0) b = m + 1;
else e = m;
}
while (m < ms && w[m].compareTo(v) <= 0) ++m;
return m;
}
public static void main(String[] args) throws Exception {
int [] a = new int[50];

final int ms = 500;
BigInteger [] ar = new BigInteger[ms];
ar[0] = BigInteger.ONE;
ar[1] = BigInteger.valueOf(2);
a[0] = 1; a[1] = 2; a[2] = 3;
for (int i = 2; i <= 42; ++i){
a[i] = a[i-1] + a[i-2];
ar[i] = BigInteger.valueOf(a[i]);
}
for (int i = 43; i < ms; ++i){
ar[i] = ar[i-1].add(ar[i-2]);
}

BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = cin.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line);

int i = 0;
while (i < line.length()
&& (' ' == line.charAt(i) || '0' == line.charAt(i)))
++i;
if (i == line.length())
break;

BigInteger aa = new BigInteger(st.nextToken());
BigInteger bb = new BigInteger(st.nextToken());

int from = leftBinarySearch(ar, ms, aa);
int to = rightBinarySearch(ar, ms, bb);
//System.out.println("" + from + ' ' + to);
System.out.println("" + (to - from - 1));
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: