Codeforces 453B. Little Pony and Harmony Chest

状压DP。。

B. 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:

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 


#include<cstring>
#include<queue>
#include<cstdio>
#include<iostream>
using namespace std;
#define ll long long
#define ERR puts("=======here========");
#define prt(k) cout<<#k"="<<k<<" "
#include<algorithm>
#include<cmath>
const int inf=0x3f3f3f3f;
int p[16]={2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53};
const int m=80017;
int dp[103][m];
int a[662],b[444];
int fact[66];
int n;
int  num[103][m],pre[103][m];
int main()
{
    int x=1<<17;
    fact[0]=fact[1]=0;
    for(int i=2;i<60;i++)
    {
        for(int j=0;j<16;j++)
        {
            if(i%p[j]==0) fact[i]|=(1<<j);
        }
    }
    cin>>n; for(int i=1;i<=n;i++) cin>>a[i];
    memset(dp,63,sizeof dp);
    dp[0][0]=0;
    for(int i=1;i<=n;i++)
    {
        for(int s=0;s<(1<<16);s++)
        {
            if(dp[i-1][s]==inf) continue;
            for(int j=1;j<60;j++)
            {
                if(s&fact[j]) continue;
                int news=s|fact[j];
                if(dp[i][news]>dp[i-1][s]+abs(a[i]-j))
                {
                    dp[i][news]=dp[i-1][s]+abs(a[i]-j);
                    num[i][news]=j;
                    pre[i][news]=s;
                }
            }
        }
    }
    int s=-1;  int ans=inf;
    for(int i=0;i<(1<<16);i++)
    {
        if(dp[n][i]<ans)
        {
            ans=dp[n][i];
            s=i;
        }
    }
    for(int i=n;i>=1;i--)
    {
        b[i]=num[i][s];
        s=pre[i][s];
    }
    for(int i=1;i<=n;i++) printf("%d ",b[i]);
}


你可能感兴趣的:(Algorithm,数据结构,算法,ACM,codeforces)