二分查找之变形

//寻找一个数,找到刚好比他小的数。

比如-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));
		}
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值