洛谷P1832 A+B Problem(再升级) 题解 完全背包方案计数

题目链接:https://www.luogu.com.cn/problem/P1832

题目大意:
给定一个正整数n,求将其分解成若干个素数之和的方案总数。

解题思路:

  • 首先找到所有 \(\le n\) 的素数;
  • 将问题转换成一个容量为 \(n\) 的背包,以及若干件体积和价值相同的物品,他们对应求出来的所有素数。
  • 求完全背包方案数

代码实现:

  • 是开始素数筛法求出所有符合要求的素数;
  • 然后完全背包计数

实现代码如下:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1010;
int n, p[maxn], cnt;
long long f[maxn];
bool np[maxn];
void init() {
    for (int i = 2; i <= n; i ++) {
        if (!np[i]) {
            p[cnt++] = i;
            for (int j = i; j <= n/i; j ++) {
                np[i*j] = true;
            }
        }
    }
}
void comp_pack(int c) {
    for (int i = c; i <= n; i ++) f[i] += f[i-c];
}
int main() {
    cin >> n;
    init();
    f[0] = 1;
    for (int i = 0; i < cnt && p[i] <= n; i ++)
        comp_pack(p[i]);
    cout << f[n] << endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/quanjun/p/12027152.html