Created
August 6, 2014 17:17
-
-
Save tamimcsedu19/d2904cfb3d13cc7305fa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <bits/stdc++.h> | |
using namespace std; | |
int n; | |
int A[105]; | |
int fact[105]; | |
int primes[50]; | |
int dp[105][140000],dpchoosen[105][140000],dptracer[105][140000]; | |
bool isPrime(int x) | |
{ | |
for(int i=2;i<x;++i) | |
if(x%i == 0) | |
return false; | |
return true; | |
} | |
void calcFact() | |
{ | |
int sz = 0; | |
for(int i=2;i<60;++i) | |
{ | |
if(isPrime(i)) | |
primes[sz++] = i; | |
} | |
for(int i=2;i<60;++i) | |
{ | |
for(int j=0;j<sz;++j) | |
if(i%primes[j] == 0) | |
fact[i]|=(1<<j); | |
} | |
} | |
int res[105],sums[105]; | |
bool vis[140000][105]; | |
int main() | |
{ | |
calcFact(); | |
cin>>n; | |
for(int i=1;i<=n;++i) | |
{ | |
fact[105] = 0; | |
sums[i] = 1000000; | |
cin>>A[i]; | |
} | |
for(int i=1;i<=n;++i) | |
for(int j=0;j<(1<<17);++j) | |
dp[i][j] = INT_MAX; | |
for(int j=0;j<(1<<17);++j) | |
dp[0][j] = 0; | |
for(int i=1;i<=n;++i) | |
for(int k=1;k<60;++k) | |
{ | |
int x = (~fact[k]) & ((1<<17)-1); | |
for(int s=x;s;s=(s-1)&x) | |
{ | |
if(dp[i-1][s]+abs(A[i]-k) < dp[i][s|fact[k]]) | |
{ | |
dp[i][s | fact[k]] = dp[i-1][s] + abs(A[i]-k); | |
dpchoosen[i][s|fact[k]] = k; | |
dptracer[i][s|fact[k]] = s; | |
} | |
} | |
} | |
int minval =INT_MAX; | |
int minidx =0; | |
for(int j=0;j<(1<<17);++j) | |
{ | |
if(dp[n][j]<minval) | |
{ | |
minval = dp[n][j]; | |
minidx = j; | |
} | |
} | |
vector<int> res; | |
res.push_back(dpchoosen[n][minidx]); | |
for(int i=n-1;i>=1;--i) | |
{ | |
res.push_back(dpchoosen[i][dptracer[i+1][minidx]]); | |
minidx = dptracer[i+1][minidx]; | |
} | |
for(int i=res.size()-1;i>=0;--i) | |
cout<<res[i]<<" "; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment