Description
描述
Let P1, P2, … ,PN, … be a sequence of prime numbers. Super-prime number is such a prime number that its current number in prime numbers sequence is a prime number too. For example, 3 is a super-prime number, but 7 is not. Index of super-prime for number is 0 iff it is impossible to present it as a sum of few (maybe one) super-prime numbers, and if such presentation exists, index is equal to minimal number of items in such presentation. Your task is to find index of super-prime for given numbers and find optimal presentation as a sum of super-primes.
令P1, P2, ..., PN为一列素数。超级素数是满足当前素数在原有的素数序列中的下标也是素数。例如,3是超级素数,而7不是。某个数字的超级素数索引是0,当且仅当它不能够表示成一系列(也可以是一个)超级素数的和,如果存在这样的表示,这个数字的超级素数索引等于该表示法所使用到的超级素数的个数和的最小值。你的任务是对于给定的数字,找到这样的一个超级素数所以以及最优的表示方法。
Input
输入
There is a positive integer number in input. Number is not more than 10000.
输入包含一个正数,数字不会大于10000。
Output
输出
Write index I for given number as the first number in line. Write I super-primes numbers that are items in optimal presentation for given number. Write these I numbers in order of non-increasing.
第一个数字输出给定数字的超级素数索引。接下来输出超级素数的表示方法,将这I个数字以非递减顺序输出。
Sample Input
样例输入
6
Sample Output
样例输出
2
3 3
Analysis
分析
首先,我们可以根据筛法求出10000以内的素数,接下来我们继续利用筛法,求出这些素数中,下标为素数的超级素数,这样我们就得到了题目中所需要的超级素数。
对于寻找一个最优的组合,我们可以使用0-1背包来解决这个问题,同时记录路径,最后输出最优解即可。
Solution
解决方案
#include <iostream> #include <memory.h> #include <vector> #include <algorithm> using namespace std; const int MAX = 10240; vector<int> P, SP; int pP[MAX], pSP[MAX], nCnt; int f[MAX], pPath[MAX]; int main() { int N; P.push_back(0); SP.push_back(0); memset(pP, 0, sizeof(pP)); memset(pSP, 0, sizeof(pSP)); for(int i = 2; i < MAX; i++) { if(pP[i] == 0) { P.push_back(i); for(int j = i + i; j < MAX; j += i) { pP[j] = 1; } } } for(int i = 2; i < P.size(); i++) { if(pSP[i] == 0) { SP.push_back(P[i]); for(int j = i + i; j < P.size(); j += i) { pSP[j] = 1; } } } while(cin >> N) { memset(f, 0, sizeof(f)); memset(pPath, 0, sizeof(pPath)); f[0] = 0; for(int i = 1; i <= N; i++) { f[i] = 214748364; } for(int i = 1; i < SP.size(); i++) { for(int j = SP[i]; j <= N; j++) { if(f[j - SP[i]] + 1 < f[j]) { f[j] = f[j - SP[i]] + 1; pPath[j] = j - SP[i]; } } } if(f[N] == 214748364) { cout << 0 << endl; } else { cout << f[N] << endl << N - pPath[N]; for(int i = pPath[N]; i; i = pPath[i]) { cout << " " << i - pPath[i]; } cout << endl; } } return 0;
这道题目主要考察最为基本的动态规划以及记录路径。