二分查找习题分析

CD

Jack and Jill have decided to sell some of their Compact Discs, while they still have some value. They have decided to sell one of each of the CD titles that they both own. How many CDs can Jack and Jill sell? 

Neither Jack nor Jill owns more than one copy of each CD. 

Input

The input consists of a sequence of test cases. The first line of each test case contains two non-negative integers N and M, each at most one million, specifying the number of CDs owned by Jack and by Jill, respectively. This line is followed by N lines listing the catalog numbers of the CDs owned by Jack in increasing order, and M more lines listing the catalog numbers of the CDs owned by Jill in increasing order. Each catalog number is a positive integer no greater than one billion. The input is terminated by a line containing two zeros. This last line is not a test case and should not be processed. 

Output

For each test case, output a line containing one integer, the number of CDs that Jack and Jill both own.

Sample Input

3 3
1
2
3
1
2
4
0 0

Sample Output

2

这道题属于模板题,知道二分查找的原理就能轻松写出代码,不过这道题在写的时候还是碰到些问题,这里把它总结一下
先把代码写出来:
 

#include<iostream>
#include<stdio.h>
#define LL long long
using namespace std;

long long  a[1001000],b[1001000];
int main(){
	std::ios::sync_with_stdio(false);
	int m,n;
	while(cin>>m>>n){
		if(m==0&&n==0){
			break;
		}
	
		for(int i=0;i<m;i++){
			cin>>a[i];
		}
		for(int i=0;i<n;i++){
			cin>>b[i];
		}
		
		LL mid;
		int ans=0;
		for(int i=0;i<m;i++){
			LL l=0;
			LL r=n-1;
			while(l<=r){
				mid=(l+r)/2;
				if(a[i]>b[mid]){
				    l=mid+1;
				}
				if(a[i]<b[mid]){
				    r=mid-1;
				}
				if(a[i]==b[mid]){
					ans++;
					//cout<<ans<<endl;
					break;
				}
				/*
				cout<<"mid="<<mid<<endl;
				cout<<"b[mid]="<<b[mid]<<endl;
				cout<<"l="<<l<<endl;
				cout<<"r="<<r<<endl;
				*/
			}
			//cout<<"******************"<<endl;
		}
		cout<<ans<<endl;	
	}
}

很简单的一段代码,需要注意这个

mid=(l+r)/2;
if(a[i]>b[mid]){
    l=mid+1;
}
if(a[i]<b[mid]){
	r=mid-1;
}
if(a[i]==b[mid]){
	ans++;
	//cout<<ans<<endl;
	break;
}

然后要注意的是输入输出的问题,因为之前从来没遇到过这样的问题,scanf,printf的时间要比cin,cout的时间短,这个我是知道的,但是我没有想到这点差别会影响到提交超时,然后把所有的输入输出全改为了scanf,printf再提交就过了,如果想用cin,cout的话需要加上

std::ios::sync_with_stdio(false);

这样就和scanf,printf一样了

猜你喜欢

转载自blog.csdn.net/Helloirbd/article/details/81778558
今日推荐