To improve the algorithm to take candy
Problem Description
Mom to buy a small B N pieces of candy! But she is not allowed to eat small B directly.
Suppose there are M pieces of candy current, each B can take a small candy P, wherein P M is not larger than a root of M prime factors. In this case, the mother will be a small piece of candy B later took P P away from sugar candy pile. Then B can then take a small sugar.
Up to now small B would like to know how much sugar can get.
Input Format
An integer N
Output Format
Up to how much sugar can take
Sample input
15
Sample Output
6
Scale data and conventions
N <= 100000
Analysis: Dynamic programming problem ~ ~
Therefore especially before it - does not create ⼀ a full EMPTY zoomed at root, the maximum values MAXN prime table, and then the screen for a prime table ⾥ number one by traversing ~
Construction ⼀ a DP [i] array representing the maximum number when the number of confectionery candies could get by when i ~
For values DP [i]: Since ⼩ B can not get below approximately every prime factor in the root number i,
Primes full table traversing prime condition EMPTY (prime [j] <= sqrt (i) && i% prime [j] == 0),
Update dp [i] values (dp [i-2 * prime [j]] + prime [j]), the maximum values of ~
即:dp[i] =max(dp[i], dp[i-2*prime[j]] + prime[j]);
#include <iostream>
#include <cmath>
using namespace std;
int prime[50000];
int dp[100005];
int book[100005];
int cnt = 0;
void create() {
int len = sqrt(100005);
for(int i = 2; i <= len; i++) {
if(book[i] == 0) {
prime[cnt++] = i;
for(int j = i * i; j <= len; j = j + i)
book[j] = 1;
}
}
}
int main() {
create();
int n;
cin >> n;
for(int i = 1; i <= n; i++) {
for(int j = 0; j < cnt; j++) {
if( prime[j] > sqrt(i))
break;
if( i % prime[j] == 0)
dp[i] = max(dp[i], dp[i-2*prime[j]] + prime[j]);
}
}
cout << dp[n];
return 0;
}