Princess Twilight went to Celestia and Luna's old castle to research the chest from the Elements of Harmony.
A sequence of positive integers bi is harmony if and only if for every two elements of the sequence their greatest common divisor equals 1. According to an ancient book, the key of the chest is a harmony sequence bi which minimizes the following expression:
You are given sequence ai, help Princess Twilight to find the key.
The first line contains an integer n (1 ≤ n ≤ 100) — the number of elements of the sequences a and b. The next line contains n integersa1, a2, ..., an (1 ≤ ai ≤ 30).
Output the key — sequence bi that minimizes the sum described above. If there are multiple optimal sequences, you can output any of them.
5
1 1 1 1 1
1 1 1 1 1
5
1 6 4 2 8
1 5 3 1 8
sl : 很傻比的状态压缩,直接背包就搞了,又傻逼了。
// by caonima
#include <bits/stdc++.h>
using namespace std;
const int MAX= 110;
const int inf = 0x3f3f3f3f;
int dp[MAX][1<<17],val[MAX],a[MAX],ans[MAX][1<<17];
int prime[MAX],vis[MAX],cur=0;
vector<int> C;
void init() {
memset(vis,0,sizeof(vis));
vis[1]=1;
for(int i=2;i<61;i++) {
if(!vis[i]) prime[cur++]=i;
for(int j=i;j<61;j+=i) vis[j]=1;
}
return ;
}
int main() {
init();
int n;
while(scanf("%d",&n)==1) {
memset(val,0,sizeof(val));
for(int i=1;i<=n;i++) {
scanf("%d",&a[i]);
}
for(int i=1;i<60;i++) {
for(int j=0;j<cur;j++) {
if(i%prime[j]==0) {
val[i]|=(1<<j);
}
}
}
for(int i=0;i<=n;i++) {
for(int j=0;j<(1<<cur);j++) dp[i][j]=inf;
}
for(int i=0;i<(1<<cur);i++) dp[0][i]=0;
for(int i=1;i<=n;i++) {
for(int j=0;j<(1<<cur);j++) {
for(int k=0;k<60;k++) {
if((j&val[k])==0) {
int res=dp[i-1][j^val[k]]+abs(k-a[i]);
if(res<dp[i][j]) {
dp[i][j]=res;
ans[i][j]=k;
}
}
}
}
}
int res=inf ,state;
for(int i=0;i<(1<<cur);i++) {
if(res>dp[n][i]) {
res=dp[n][i];
state=i;
}
}
// printf("%d ",ans[n][0]);
for(int i=n;i>=1;i--) {
C.push_back(ans[i][state]);
int k=ans[i][state];
state=state^(val[k]);
}
for(int i=C.size()-1;i>=0;i--) {
printf("%d ",C[i]);
}
printf(" ");
}
return 0;
}
#define debug() printf("sss");
using namespace std;
const int inf = 0x3f3f3f3f;
const int MAX = 110;
int cur=0,vis[MAX],prime[MAX],state[MAX];
vector<int> C;
int dp[MAX][1<<17],a[MAX],b[MAX],n,res[MAX][1<<17];
void init() {
for(int i=2;i<MAX;i++) {
if(!vis[i]) prime[cur++]=i;
for(int j=i;j<MAX;j+=i) vis[j]=1;
}
memset(state,0,sizeof(state));
for(int i=2;i<70;i++) {
for(int j=0;j<18;j++) {
if(i%prime[j]==0) state[i]|=(1<<j);
}
}
}
int dfs(int pos,int s) {
if(pos>n) return 0;
if(~dp[pos][s]) return dp[pos][s];
int ans=inf;
for(int i=1;i<60;i++) {
if(s&state[i]) continue;
int t=dfs(pos+1,s|state[i])+abs(i-a[pos]);
if(ans>t) {
ans=t;
res[pos][s]=i;
}
}
return dp[pos][s]=ans;
}
int main() {
init();
while(scanf("%d",&n)==1) {
for(int i=1;i<=n;i++) {
scanf("%d",&a[i]);
}
memset(dp,-1,sizeof(dp));
dfs(1,0);
int s=0;
for(int i=1;i<=n;i++) {
C.push_back(res[i][s]);
int k=res[i][s];
s=s|(state[k]);
}
for(int i=0;i<C.size();i++) {
printf("%d ",C[i]);
}
printf(" ");
}
}