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;
}