素数筛+完全背包+路径记录
AC代码:
#include <stdio.h>
#include <vector>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX = 100010;
const int INF = 0x3f3f3f3f;
bool IsPrime[MAX];
int Prime[MAX],SPrime[MAX],pn,cnt;
int dp[MAX],from[MAX];
void make_prime(){
memset(IsPrime, true, sizeof(IsPrime));
IsPrime[0] = IsPrime[1] = false;
pn = 1;
for(int i=2; i<MAX; i++){
if(IsPrime[i]) Prime[pn++] = i;
for(int j=1; j<pn && Prime[j]*i < MAX; j++){
IsPrime[Prime[j]*i] = false;
if(i % Prime[j] == 0) break;
}
}
}
int main(){
int n; cin >> n;
make_prime();
cnt = 1;
for(int i=1; i<=pn; i++)
if(IsPrime[i]) SPrime[cnt++] = Prime[i];
memset(dp, 0x3f, sizeof(dp));
dp[0] = 0;
for(int i=1; i<cnt; i++){///完全背包
for(int j=SPrime[i]; j<=n; j++){
if(dp[j-SPrime[i]] + 1 < dp[j]){
dp[j] = dp[j-SPrime[i]] + 1;
from[j] = j-SPrime[i];
}
}
}
if(dp[n] == INF) {cout << "0" << endl; return 0;}
printf("%d\n%d",dp[n], n-from[n]);
for (int i=from[n]; i; i=from[i])
printf(" %d",i-from[i]);
printf("\n");
///system("pause");
return 0;
}