[CF453B]Little Pony and Harmony Chest--状压dp

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

Examples
input
Copy
5
1 1 1 1 1
output
Copy
1 1 1 1 1 
input
Copy
5
1 6 4 2 8
output
Copy
1 5 3 1 8 

题解: ....(赶紧补)

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int p[]={2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53};
 4 const int num=(1<<16)-1;
 5 int dp[107][num+7];
 6 int choice[107][num+7];
 7 int a[107],b[107],status[67];
 8 int n;
 9 int cal(int x) {
10     int sum=0;
11     for (int i=0;i<16;i++)
12         if (x%p[i]==0)
13             sum+=(1<<i);
14     return sum;
15 }
16 int main()
17 {
18     cin>>n;
19     for(int i=1;i<=n;i++)  cin>>a[i];
20     for(int i=1;i<59;i++)  status[i]=cal(i);
21     memset(dp,0x3f,sizeof(dp));
22     dp[0][0]=0;
23     for(int i=1;i<=n;i++) 
24         for(int j=0;j<=num;j++)  // num 应该等于号
25             for(int k=1;k<59;k++) 
26                 if((j|status[k])==j) {
27                     if(dp[i][j]>dp[i-1][j-status[k]]+abs(k-a[i])) {
28                         dp[i][j]=dp[i-1][j-status[k]]+abs(k-a[i]);
29                         choice[i][j]=k;
30                     }
31                 }
32     int ans=0x3f3f3f3f, k;
33     for(int i=0;i<=num;i++) // num 这也是啊
34         if(dp[n][i]<ans) {
35             ans=dp[n][i];
36             k=i;
37         }
38     for (int i=n;i>=1;i--) {
39         b[i]=choice[i][k];
40         k-=status[b[i]];
41     }
42     for (int i=1;i<n;i++)
43         printf("%d ", b[i]);
44     printf("%d
",b[n]);
45     return 0;
46 }

 

原文地址:https://www.cnblogs.com/xidian-mao/p/11481370.html