洛谷P1832 A+B Problem(再升级) [2017年4月计划 动态规划03]
P1832 A+B Problem(再升级)
题目背景
·题目名称是吸引你点进来的
·实际上该题还是很水的
题目描述
·1+1=? 显然是2
·a+b=? 1001回看不谢
·哥德巴赫猜想 似乎已呈泛滥趋势
·以上纯属个人吐槽
·给定一个正整数n,求将其分解成若干个素数之和的方案总数。
输入输出格式
输入格式:一行:一个正整数n
输出格式:一行:一个整数表示方案总数
输入输出样例
输入样例#1:
7
输出样例#1:
3
说明
【样例解释】
7=7 7=2+5
7=2+2+3
【福利数据】
【输入】 20
【输出】 26
【数据范围及约定】
对于30%的数据 1<=n<=10
对于100%的数据,1<=n<=10^3
埃拉托斯提尼筛法打素数表。
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> inline long long read() { long long x = 0;char ch = getchar();char c = ch; while(ch > '9' || ch < '0')c = ch,ch = getchar(); while(ch <= '9' && ch >= '0')x = x * 10 + ch - '0',ch = getchar(); if(c == '-')return -1 * x; return x; } const int INF = 0x3f3f3f3f; const int MAXN = 0x4f4f4f4f; bool b[MAXN]; int main() { long long n = read(); for(int i = 2;i*i <= n;i ++) { if(!b[i]) { for(int j = i*2;j <= n;j += i) { b[j] = true; } } } long long ans = 0; for(int i = 2;i <= n;i ++) { if(!b[i]) { printf("%d,", i); ans ++; } } printf("\n%d", ans); return 0; }
素数输出到文件,复制粘贴过来直接用。
使用背包统计次数,是一个完全背包的小变形(如果真正理解了完全背包,直接看代码就能懂)。初始化为f[0] = 1,因为f[v[i]] = 1,转移时f[v[i]] = f[v[i] - v[i]]。
代码如下。
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> inline int read() { int x = 0;char ch = getchar();char c = ch; while(ch > '9' || ch < '0')c = ch,ch = getchar(); while(ch <= '9' && ch >= '0')x = x * 10 + ch - '0',ch = getchar(); if(c == '-')return -1 * x; return x; } const int INF = 0x3f3f3f3f; int prime[170] = {0,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997}; int n; long long f[1010]; int main() { n = read(); f[0] = 1; for(int i = 1;prime[i] <= n && i <= 168;i ++) { for(int j = prime[i];j <= n;j ++) { f[j] += f[j - prime[i]]; } } std::cout<<f[n]; return 0; }