【POJ 3763】CD

                                           CD

Time Limit: 12000/6000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1253    Accepted Submission(s): 542


 

Problem Description

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

题意:A和B分别拥有一些碟片,每种碟片他们自己最多拥有1份,求A和B有多少相同的CD。

使用数组方法存放和查询数据会内存超限,用二分查找方法每个数据最多查找20次就能找到。

代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<map>
using namespace std;
#define closeio std::ios::sync_with_stdio(false)

int a[1000005],n,m;
inline void read(int &x)                //读入优化
{
	x=0;char c=getchar();
	while(c<'0' || c>'9')c=getchar();
	while(c>='0' && c<='9')
	{
		x=x*10+c-'0';
		c=getchar();
	} 
}

int ss(int t)
{
	int i,l=0,r=n-1;
	while(l<=r)
	{
		int mid=(l+r)>>1;
		if(a[mid]==t)
		return 1;
		else if(a[mid]>t)
		r=mid-1;
		else
		l=mid+1;
	}
	return 0;
}

int main() 
{
	int i,t,s;
	closeio;
	while(cin>>n>>m,n+m)
	{
		s=0;
		for(i=0;i<n;i++)
		read(a[i]);
		for(i=0;i<m;i++)
		{
			read(t);
			if(ss(t))
				s++;
		}
		cout<<s<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Xylon_/article/details/81743379
POJ
cd