Description
Princess Twilight went to Celestia and Luna’s old castle to research the chest from the Elements of Harmony.
A sequence of positive integers
b
i
b_i
bi is harmony if and only if for every two elements of the sequence their greatest common divisor equals
1
1
1. According to an ancient book, the key of the chest is a harmony sequence
b
i
b_i
bi which minimizes the following expression:
You are given sequence
a
i
a_i
ai, help Princess Twilight to find the key.
Input
The first line contains an integer
n
(
1
≤
n
≤
100
)
n~(1 ≤ n ≤ 100)
n (1 ≤ n ≤ 100) — the number of elements of the sequences a and b. The next line contains n integers
a
1
,
a
2
,
.
.
.
,
a
n
(
1
≤
a
i
≤
30
)
a_1, a_2, ..., a_n~(1 ≤ a_i ≤ 30)
a1, a2, ..., an (1 ≤ ai ≤ 30).
Output
Output the key — sequence
b
i
b_i
bi that minimizes the sum described above. If there are multiple optimal sequences, you can output any of them.
Examples
Input
5
1 1 1 1 1
Output
1 1 1 1 1
Input
5
1 6 4 2 8
Output
1 5 3 1 8
Solution
因为
{
1
,
1
,
1
,
.
.
.
1
}
\left\{1,1,1,...1\right\}
{1,1,1,...1} 总是一组符合条件的结果,所以
b
i
b_i
bi 的最大值始终小于59
要使得任意的
b
i
,
b
j
b_i, b_j
bi,bj 的
G
c
d
=
=
1
Gcd == 1
Gcd==1 ,只要任意两个都没有相同的素因子即可
又发现小于59的质数只有16个,我们可以用状压来表示素因子的出现情况
定义
D
P
[
i
]
[
j
]
:
DP[i][j] :
DP[i][j]: 考虑前 i 个数,质因子出现情况为 j 时的最小耗费
这里还需要记录路径,那么我们就再记录一下前 i 个数,质因子情况为 j 时的最优选择之一
b
e
s
t
[
i
]
[
j
]
best[i][j]
best[i][j] 即可
Hint
这题数据好像很水,有博主素数表打错了都能A…
Code
#include <bits/stdc++.h>
#define endl '\n'
#define ls rt << 1
#define rs rt << 1 | 1
#define pb push_back
#define mp(a,b) make_pair(a,b)
#define clr(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int maxn = 100 + 5;
int prime[] = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53};
int pos[55];
int a[maxn];
int dp[maxn][(1 << 16)+5];
int st[62];
int cal(int x){
int res = 0,cnt = 0,p[18] = {0};
for(int i = 2;i * i <= x;++i){
if(x % i == 0){
p[cnt++] = i;while(x % i == 0) {x /= i;}
}
}
if(x > 1) p[cnt++] = x;
for(int i = 0;i < cnt;++i){
res |= (1 << pos[p[i]]);
}
return res;
}
int best[maxn][(1<<16)+5];
int ans[maxn];
void solve(int n,int sta){
if(n == 0) return ;
int j = best[n][sta];
ans[n] = j;
solve(n-1,sta^st[j]);
}
int main(){
int n;scanf("%d",&n);
for(int i = 1;i <= n;++i){
scanf("%d",&a[i]);
}
for(int i = 0;i < 16;++i){
pos[prime[i]] = i;
}
for(int i = 1;i < 60;++i){
st[i] = cal(i);
}
clr(dp,0x3f);
int res = INF;
dp[0][0] = 0;
for(int i = 1;i <= n;++i){
for(int k = 0;k < (1 << 16);++k){
if(dp[i-1][k] == INF) continue;
for(int j = 1;j < 60;++j){
int s = st[j];
if(k & s) continue;
if(dp[i-1][k] + abs(a[i] - j) <= dp[i][s|k]){
best[i][s|k] = j;
dp[i][s|k] = dp[i-1][k] + abs(a[i]-j);
}
}
}
}
int sta = 0;
for(int i = 0;i < (1 << 16);++i) {
if(best[n][i] != 0 && dp[n][i] < res){
res = dp[n][i];
sta = i;
}
}
solve(n,sta);
for(int i = 1;i <= n;++i) {
printf("%d%c", ans[i],i == n ? '\n' : ' ');
}
return 0;
}