-
Notifications
You must be signed in to change notification settings - Fork 0
/
Game Of Subsets
168 lines (128 loc) · 4.04 KB
/
Game Of Subsets
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
//{ Driver Code Starts
//Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function Template for C++
//{ Driver Code Starts
//Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function Template for C++
int dp[100010][1024];
class Solution{
public:
int goodSubsets(vector<int> &arr, int n){
const int mod = 1e9 + 7;
map<int,int> bits = { {2, 0},
{3, 1},
{5, 2},
{7, 3},
{11,4},
{13, 5},
{17, 6},
{19, 7},
{23, 8},
{29, 9}
};
vector<int> mask(31, 0);
for(int i = 2; i < 31; i++){
int currentMask = 0;
bool ok = 1;
int val = i;
for(int j = 2; j * j <= val; j++){
while(val % j == 0){
int pos = bits[j];
if((currentMask >> pos) & 1){
ok = 0;
break;
}
currentMask |= (1 << pos);
val /= j;
}
if(!ok)
break;
}
if(val > 1){
int pos = bits[val];
if((currentMask >> val) & 1)
ok = 0;
else
currentMask |= (1 << pos);
}
if(!ok)
mask[i] = 0;
else
mask[i] = currentMask;
}
dp[0][0] = 0;
for(int i = 1; i < 1024; i++)
dp[0][i] = 1;
int count = 0;
for(int i = 1; i < n + 1; i++){
if(arr[i - 1] == 1)
++count;
for(int currentMask = 0; currentMask < 1024; currentMask++){
int val = arr[i - 1];
if(val == 1){
dp[i][currentMask] = dp[i - 1][currentMask];
continue;
}
bool ok = 1;
int finalMask;
if(mask[val]){
if(mask[val] & currentMask)
ok = 0;
else
finalMask = mask[val] | currentMask;
}
else{
ok = 0;
}
if(ok){
int x = dp[i - 1][finalMask];
int y = dp[i - 1][currentMask];
dp[i][currentMask] = (x + y) % mod;
}
else{
dp[i][currentMask] = dp[i - 1][currentMask];
}
}
}
auto expo = [](long long a, int n, int mod) -> long long {
long long res = 1;
while(n){
if(n & 1) {
res = (res * a) % mod;
--n;
}
else {
a = (a * a) % mod;
n >>= 1;
}
}
return res;
};
long long ways = expo(2, count, mod);
int ans = (dp[n][0] * ways) % mod;
return ans;
}
};
//{ Driver Code Starts.
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
vector<int> a(n);
for(int i=0;i<n;i++){
cin>>a[i];
}
Solution ob;
cout<<ob.goodSubsets(a, n)<<endl;
}
return 0;
}
// } Driver Code Ends