D. Little Pony and Harmony Chest
time limit per test
4 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output


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:

Codeforces Round #259 (Div. 2) D

You are given sequence ai, help Princess Twilight to find the key.

Input

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

Output the key — sequence bi that minimizes the sum described above. If there are multiple optimal sequences, you can output any of them.

Sample test(s)
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 

 

 sl : 很傻比的状态压缩,直接背包就搞了,又傻逼了。

 

 // by caonima

// hehe
#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\n",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("\n");
    }
    return 0;
}
);
    }
}

相关文章: