您的位置:首页 > 其它

HDU 3763 CD【二分查找】

2014-12-24 07:13 369 查看
解题思路:给出两个数列an,bn,求an和bn中相同元素的个数
因为注意到n的取值是0到1000000,所以可以用二分查找来做,因为题目中给出的an,bn,已经是单调递增的,所以不用排序了,对于输入的每一个b[i],查找它在an数列中是否存在。存在返回值为1,不存在返回值为0

CD

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

[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
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.

[align=left]Output[/align]
For each test case, output a line containing one integer, the number of CDs that Jack and Jill both own.

[align=left]Sample Input[/align]

3 3
1
2
3
1
2
4
0 0

[align=left]Sample Output[/align]

2

#include<stdio.h>
#include<string.h>
int a[1000005],b[1000005];
int bsearch(int a[],int n,int t)
{
int x,y,m;
x=1;
y=n;
while(x<=y)
{
m=(x+y)/2;
if(a[m]==t)
return 1;
else
{
if(a[m]>t)
y=m-1;
else
x=m+1;
}

}
return 0;
}
int main()
{
int n,m,i,t,num;
while(scanf("%d %d",&n,&m)!=EOF&&(n||m))
{
num=0;
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=1;i<=m;i++)
{
scanf("%d",&b[i]);
num+=bsearch(a,n,b[i]);
}
printf("%d\n",num);
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: