【SSL】2378 &【Luogu】P1102A-B number pair

【SSL】2378 &【Luogu】P1102A-B number pair

Title description

Questioning is a painful thing!

If you read the same topic too much, there will be aesthetic fatigue, so I discarded the familiar A+B Problem and switched to AB haha!

Well, the question is this: Given a string of numbers and a number C, it is required to calculate the number of all pairs of A−B=C (the same number in different positions is counted as different pairs).

Input format

Enter a total of two lines.

In the first line, two integers N and C.

In the second line, N integers are used as the string to be processed.

Output format

One line indicates the number of pairs that satisfy A−B=C contained in the string.

Sample input and output

enter
4 1
1 1 2 3
Output
3

Instructions/tips

For 75% of the data, 1≤N≤2000.

For 100% data, 1≤N≤200000.

Ensure that all input data is within the 32-bit signed integer range.

Ideas

AB=C
B+C=A
uses HASH.
Use an array to store the number of occurrences.
Special judgment 0.

Code

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
long long a[200010],n,c,hs[1000010],cs[1000010],an,bn,m=1000000,p=900007; 
long long HASH(long long x)//函数 
{
    
    
	x%=p;x+=p;
	return x%p;
}
long long locate(long long x)//x定位 
{
    
    
	long long i,w=HASH(x);
	for(i=0;i<m&&hs[(w+i)%m]!=0&&hs[(w+i)%m]!=x;i++);
	return (w+i)%m;
}
int main()
{
    
    
	long long i,t,n,c,x,w,ans=0,zero=0;
	scanf("%lld%lld",&n,&c);
	for(i=1;i<=n;i++)
	{
    
    
		scanf("%lld",&a[i]);
		x=a[i]+c;
		if(x==0)//特判0 
			zero++;
		else
		{
    
    
			w=locate(x);//插入x 
			hs[w]=x;
			cs[w]++;
		}
	}
	for(i=1;i<=n;i++)
	{
    
    
		if(a[i]==0)//特判0 
			ans+=zero;
		else
		{
    
    
			w=locate(a[i]);
			ans+=(hs[w]==a[i])*cs[w];
		}
	}
	printf("%lld",ans);
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_46975572/article/details/112972410