一 原题
Petya was late for the lesson too. The teacher gave him an additional task. For some array a Petya should find the number of different ways to select non-empty subset of elements from it in such a way that their product is equal to a square of some integer.
Two ways are considered different if sets of indexes of elements chosen by these ways are different.
Since the answer can be very large, you should find the answer modulo 109 + 7.
First line contains one integer n (1 ≤ n ≤ 105) — the number of elements in the array.
Second line contains n integers ai (1 ≤ ai ≤ 70) — the elements of the array.
Print one integer — the number of different ways to choose some elements so that their product is a square of a certain integer modulo 109 + 7.
4 1 1 1 1
15
4 2 2 2 2
7
5 1 2 4 5 8
7
In first sample product of elements chosen by any way is 1 and 1 = 12. So the answer is 24 - 1 = 15.
In second sample there are six different ways to choose elements so that their product is 4, and only one way so that their product is 16. So the answer is 6 + 1 = 7.
二 分析
三 代码
#include<iostream>
#include<cstring>
using namespace std;
const int inf = 72;
const int mod = 1e9 + 7;
const int maxn = 1e5 + 10;
int n, times[inf];
bool prime[inf];
int mask[inf];
long long pow[maxn];
long long f1[inf], f2[inf];
long long dp[2][1 << 20]; // total 19 prime numbers in [1, 70]
void setMask() {
for(int i = 1; i < inf; i++) {
int cnt = 0;
for(int j = 1; j <= i; j++) {
if(!prime[j]) continue;
int x = i;
while(x % j == 0) {
x /= j;
mask[i] ^= (1 << cnt);
}
cnt++;
}
}
}
int main() {
ios::sync_with_stdio(false);
cin >> n;
int val;
for(int i = 0; i < n; i++) {
cin >> val;
times[val]++;
}
// prepare f1 and f2
pow[0] = 1;
for(int i = 1; i < maxn; i++) {
pow[i] = (pow[i - 1] + pow[i -1]) % mod;
}
for(int i = 0; i < inf; i++) {
if(times[i] == 0)
f1[i] = 1, f2[i] = 0;
else
f1[i] = f2[i] = pow[times[i] - 1];
}
// prepare mask
for(int i = 2; i < inf; i++) {
prime[i] = true;
for(int j = 2; j * j <= i; j++) {
if(i % j == 0) {
prime[i] = false;
break;
}
}
}
setMask();
// begin dp
dp[0][0] = 1;
for(int i = 1; i <= 70; i++) {
int cur = i % 2;
memset(dp[cur], 0, sizeof(dp[cur]));
for(int j = 0; j < (1 << 20); j++) {
dp[cur][j] += (dp[1 - cur][j] * f1[i]) % mod;
dp[cur][j] %= mod;
dp[cur][j ^ mask[i]] += (dp[1 - cur][j] * f2[i]) % mod;
dp[cur][j] %= mod;
}
}
cout << (dp[0][0] - 1) % mod << endl; // due to 70 is even, it's dp[0][0]
return 0;
}

本文介绍了一道算法题目,任务是计算给定数组中元素的所有非空子集,找出那些子集的乘积能构成完全平方数的方法数量。通过使用动态规划和素数分解的思想,文章详细阐述了解决这一问题的具体步骤。
1626

被折叠的 条评论
为什么被折叠?



