【洛谷 P1102】A-B数对【二分&哈希表】

题目描述

出题是一件痛苦的事情!
相同的题目看多了也会有审美疲劳,于是我舍弃了大家所熟悉的 A+B Problem,改用 A-B 了哈哈!
好吧,题目是这样的:给出一串数以及一个数字 CC,要求计算出所有 A - B = CA−B=C 的数对的个数(不同位置的数字一样的数对算不同的数对)。

输入格式

输入共两行。
第一行,两个整数 N, CN,C。
第二行,NN 个整数,作为要求处理的那串数。

输出格式

一行,表示该串数中包含的满足 A - B = CA−B=C 的数对的个数。

输入输出样例

输入 #1

4 1
1 1 2 3

输出 #1

3

分析:

可直接用哈希表
也可以直接二分 两次二分

二分 CODE:

#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int n,c,a[200010];
int main(){
	scanf("%d%d",&n,&c);
	for(int i=1;i<=n;i++) scanf("%d",&a[i]);
	sort(a+1,a+n+1);  //排序
	long long ans=0;
	for(int i=1;i<=n;i++) 
		ans+=upper_bound(a+1,a+n+1,a[i]-c)-lower_bound(a+1,a+n+1,a[i]-c);  //STL二分查找
	printf("%lld",ans);
	return 0;
}

哈希 CODE:

#include<iostream>
#include<cstdio>
#include<algorithm> 
#include<cstring>
#include<cmath>
#define p 4000037
using namespace std;
long long a[p],b[200010],c[p];
long long n,C,x,m,ans;
long long hash(long long x)
{
	return x%p;
}
long long locate(long long x)
{
	long long i=0;
	m=hash(abs(x));
	while(a[hash(i+m)]!=x&&c[hash(i+m)]!=0)
		i++;
	return hash(i+m);
}
int main()
{
	scanf("%lld%lld",&n,&C);
	for(int i=1;i<=n;i++)
	{
	 	scanf("%lld",&b[i]);
	 	a[locate(b[i])]=b[i];      //存数
	 	c[locate(b[i])]++;    //存出现的次数
	}
	for(int i=1; i<=n; i++)
	{
		ans+=c[locate(b[i]-C)%p];
	} 
    cout<<ans;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/dgssl_xhy/article/details/107466969