您的位置:首页 > 其它

hdu 3763 CD(二分查找)

2017-11-19 19:19 309 查看
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中有几个相同的元素,其中集合中元素已经按升序排好

起初 暴力 。。 但看到one billion 感觉事情并不是这么简单

但是还是暴力了 开到1千万 竟然过了 ,数据有点弱, 但还是用二分更正确

1千万暴力:

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
bool a[10000001];
//int b[10000001];
int main ()
{
int x, y;
while (scanf("%d%d",&x,&y),x+y!=0)
{
memset(a, 0, sizeof(a));
//memset(b, 0, sizeof(b));
for (int i=0; i<x; i++)
{
int m;
scanf("%d",&m);
a[m]=true;

}
int num=0;
for (int i=0; i<y; i++)
{
int m;
scanf("%d",&m);
if (a[m]==true)
num++;

}
printf ("%d\n",num);
}
}


二分写法

#include<cstdio>
using namespace std;

int a[1000005];

int search(int key,int n)
{
int low=0,mid,high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==key)
return 1;
else if(a[mid]<key)
low=mid+1;
else
high=mid-1;
}
return 0;
}

int main()
{
int ans;
int flag;
int key;
int n,m;
while(scanf("%d%d",&n,&m),n||m)
{
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
ans=0;
for(int i=0; i<m; i++)
{
scanf("%d",&key);
ans=ans+search(key,n);
}
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: