1857F - Sum and Product - CodeForces Solution


math

Please click on ads to support us..

C++ Code:

#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <set>
#include <vector>
#include <cmath>
#include <unordered_map>
#include <map>
#define x first
#define y second

using namespace std;

typedef long long LL;

typedef pair<LL,LL> PII;

typedef pair<PII,int> PIII;

typedef pair<int,string> PIS;

const int N = 200010,M = N * 2,mod = 1e9 + 7;

int n,m;
int f[N],g[N];

PII get(LL a,LL b)
{
	LL p = sqrt(abs(a * a - b * 4));
	if(p * p != abs(a * a - b * 4)) return {0,0};
	return {(p - a) / 2,(p + a) / 2};
}

int main(){
	int T;
	cin >> T;
	while(T--)
	{
		map<int,int> mp;
		scanf("%d",&n);
		for(int i = 1;i <= n;i++) scanf("%d",&f[i]),mp[f[i]]++;
		
		scanf("%d",&m);
		while(m--)
		{
			LL a,b;
			cin >> a >> b;
			PII k = get(a,b);
			LL res = 0;
			if(mp.count(-(k.x)) != 0 && mp.count(k.y) != 0)
			{
				if(-(k.x) == k.y)
				{
					int p = mp[k.y];
					res += (LL)p * (p - 1) / 2;
				}
				else res += (LL)mp[-(k.x)] * mp[k.y];
			}
//			if(mp.count(k.x) != 0 && mp.count(-(k.y)) != 0)
//			{
//				if(-(k.y) == k.x)
//				{
//					int p = mp[k.x];
//					res += (LL)p * (p - 1) / 2;
//				}
//				else res += (LL)mp[k.x] * mp[-(k.y)];
//			}
			cout << res << '\n';
		}
		cout << '\n';
	}
	return 0;
}


Comments

Submit
0 Comments
More Questions

787. Cheapest Flights Within K Stops
779. K-th Symbol in Grammar
701. Insert into a Binary Search Tree
429. N-ary Tree Level Order Traversal
739. Daily Temperatures
647. Palindromic Substrings
583. Delete Operation for Two Strings
518. Coin Change 2
516. Longest Palindromic Subsequence
468. Validate IP Address
450. Delete Node in a BST
445. Add Two Numbers II
442. Find All Duplicates in an Array
437. Path Sum III
436. Find Right Interval
435. Non-overlapping Intervals
406. Queue Reconstruction by Height
380. Insert Delete GetRandom O(1)
332. Reconstruct Itinerary
368. Largest Divisible Subset
377. Combination Sum IV
322. Coin Change
307. Range Sum Query - Mutable
287. Find the Duplicate Number
279. Perfect Squares
275. H-Index II
274. H-Index
260. Single Number III
240. Search a 2D Matrix II
238. Product of Array Except Self