[Problem solution] P1102 AB number pairs

topic

Questioning is a painful thing!

If you read the same topic too much, there will be aesthetic fatigue, so I gave up 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 A-B = C (the same number pairs in different positions count as different pairs).

Input format There are
two lines of input.

In the first line, two integers N, C.

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

Output format
One line, indicating the number of pairs satisfying A-B = C contained in the string.

Input and output sample
input
4 1
1 1 2 3
output
3

Ideas

If you try AB=C one by one, the time complexity is n^2 and it will time out
What if you use numbers as subscripts? a[s] represents the number of occurrences of the number s, if you want to find a qualified ab=c (sb=c), add a[sb] directly, and then multiply the number of occurrences of the number s.
But this space is obviously not enough (all input data are in the range of 32-bit signed integers)
map can solve this problem well

program

#include<bits/stdc++.h>
using namespace std;
int n,c;
long long anss; //最后输出的答案要开long long,因为第三个测试点的数据范围已经超出了int 
map <long long ,long long> a; //a[数字s]=数字s出现的次数 
int main()
{
    
    
	scanf("%d%d",&n,&c);
	for (int i=1;i<=n;i++)
	{
    
    
		int s;
		cin>>s;
		a[s]++;
	}
	map<long long,long long>::iterator it;
	for (it=a.begin();it!=a.end();it++)
	  anss+=a[it->first-c]*it->second; 
	  //it->first代表a,it->first等价于a-c,也就是b,符合条件的b出现的次数就是满足a-c=b的数对的个数 
	  //后面还要乘 it->second是因为可能有多个a,就需要乘a的数目 
	cout<<anss<<endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45485187/article/details/108598216