HDU-3763-CD(二分)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3763

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

有道类似的题:https://blog.csdn.net/qq_40482358/article/details/81431890

同样的方法:

ac:

//一页 27行就很舒服 
#include<stdio.h>
#include<string.h>  
#include<math.h>  
  
//#include<map>   
//#include<set>
#include<deque>  
#include<queue>  
#include<stack>  
#include<bitset> 
#include<string>  
#include<iostream>  
#include<algorithm>  
using namespace std;  

#define ll long long  
#define INF 0x3f3f3f3f  
#define mod 998244353
//#define max(a,b) (a)>(b)?(a):(b)
//#define min(a,b) (a)<(b)?(a):(b) 
#define clean(a,b) memset(a,b,sizeof(a))// 水印 
//std::ios::sync_with_stdio(false);

ll arr1[1000100],arr2[1000100];
int n,m;

int main()
{
	while(scanf("%d%d",&n,&m))
	{
		if(n==0&&m==0)
			break;
		for(int i=1;i<=n;++i)
			scanf("%lld",&arr1[i]);
		for(int i=1;i<=m;++i)
			scanf("%lld",&arr2[i]);
		ll sum=0;
		for(int i=1;i<=n;++i)
		{
			int l=0,r=m+1,mid;
			while(r-l>1)//找最左边的 
			{
				mid=(r+l)>>1;
				if(arr2[mid]>arr1[i])
					r=mid-1;
				else if(arr2[mid]<arr1[i])
					l=mid;
				else
					r=mid;
			}
			int L=r;
			r=m+1,l=0;
			while(r-l>1)//找最右边的 
			{
				mid=(r+l)>>1;
				if(arr2[mid]>arr1[i])
					r=mid;
				else if(arr2[mid]<arr1[i])
					l=mid+1;
				else
					l=mid;
			}
			int R=l;
			//cout<<L<<" "<<R<<endl;
			if(R>=L&&arr2[L]==arr1[i]&&arr2[R]==arr1[i])
				sum=sum+R-L+1;
		}
		printf("%lld\n",sum);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_40482358/article/details/81711039