atcoder abc 342 D - Square Pair(数学)

本文介绍了AtcoderABC342D题目的解决方案,涉及分解一个数的质因数,利用哈希表存储奇数数量的质因数对,最后计算符合条件的平方数对的数量。更新后的代码简化了数据结构,只需要记录每个数分解后奇数质因数的乘积。
摘要由CSDN通过智能技术生成

atcoder abc 342 D - Square Pair(数学)

题目链接

思路

一个数分解质因数,若分解的某个质因数的数目为偶数,可以自成平方数;若为奇数,则需要和其他数匹配才可以,而被匹配的这个数满足分解的为奇数数目的质因数与前面的数相同。
所以我们可以开一个哈希表,存储一个数分解的为奇数数目的质因数,对于0,需要特判一下,它与其他任何数都可组成平方数

代码

#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
const int N = 2e5 + 10;
using ll = long long;

int n;
int a[N];
map<vector<int>, int> hask;
ll ans = 0;

void divide(int x) {
	vector<int> res;
	for(int i=2;i<=x/i;i++)
		if (x % i == 0) {
			int s = 0;
			while (x % i == 0) x /= i, s++;
			if (s & 1) res.push_back(i);
		}
	if (x > 1) res.push_back(x);
	sort(res.begin(), res.end());
	ans += hask[res];
	hask[res]++;
}

int main() {
	cin >> n;
	for (int i = 1; i <= n; i++) cin >> a[i];
	int cnt = 0;
	for (int i = 1; i <= n; i++)
		if (a[i])
			divide(a[i]);
		else cnt++;
	ans += (ll)(n - cnt) * cnt + ((ll)cnt * (cnt - 1)) / 2;
	cout << ans << endl;
	return 0;
}

update

其实只要满足分解的为奇数数目的质因数乘积相同就可以了,直接开一个map<int,int>,然后分解质因数时把数目为偶数的质因数除去就OK了

#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
const int N = 2e5 + 10;
using ll = long long;

int n;
int a[N];
map<int, int> hask;
ll ans = 0;

void divide(int x) {
	for(int i=2;i<=x/i;i++)
		if (x % (i * i) == 0) 
			while (x % (i * i) == 0) x /= (i * i);
	ans += hask[x];
	hask[x]++;
}

int main() {
	cin >> n;
	for (int i = 1; i <= n; i++) cin >> a[i];
	int cnt = 0;
	for (int i = 1; i <= n; i++)
		if (a[i])
			divide(a[i]);
		else cnt++;
	ans += (ll)(n - cnt) * cnt + ((ll)cnt * (cnt - 1)) / 2;
	cout << ans << endl;
	return 0;
}
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值