Codeforces 453 B. 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.

Codeforces 453 B. Little Pony and Harmony Chest_第1张图片

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 containsn integers a1, 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 <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int prime[]={2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53};
const int pr=16;
const int INF=0x3f3f3f3f;

int n,a[200],ans[200];
int dp[200][80000],opt[60],tis[200][80000],to[200][80000];

int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++) scanf("%d",a+i);
	memset(dp,63,sizeof(dp));
	for(int i=1;i<=60;i++)	
		for(int j=0;j<pr;j++)	
			if(i%prime[j]==0)
				opt[i]|=(1<<j);
	dp[0][0]=0;
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=60;j++)
		{
			for(int k=0;k<(1<<pr);k++)
			{
				if(!(k&opt[j]) && dp[i][k|opt[j]]>dp[i-1][k]+abs(a[i]-j))	
				{
					dp[i][k|opt[j]]=dp[i-1][k]+abs(a[i]-j);
					tis[i][k|opt[j]]=j;
					to[i][k|opt[j]]=k;
				}
			}
		}
	}
	int mx=INF,node=-1;
	for(int i=0;i<(1<<pr);i++)
	{
		if(mx>dp[n][i])
		{
			mx=dp[n][i];
			node=i;
		}
	}
	for(int i=n;i>=1;i--)
	{
		ans[i]=tis[i][node];
		node=to[i][node];
	}
	for(int i=1;i<=n;i++)
	{
		printf("%d ",ans[i]);
	}
	return 0;
}




你可能感兴趣的:(Codeforces 453 B. Little Pony and Harmony Chest)