1597 有限背包计数问题

来源:互联网 发布:程序员杂志 2016 pdf 编辑:程序博客网 时间:2024/06/05 08:08

1597 有限背包计数问题
题目来源: 原创
基准时间限制:2.333 秒 空间限制:131072 KB 分值: 160 难度:6级算法题
收藏
关注
你有一个大小为n的背包,你有n种物品,第i种物品的大小为i,且有i个,求装满这个背包的方案数有多少
两种方案不同当且仅当存在至少一个数i满足第i种物品使用的数量不同

Input

第一行一个正整数n
1<=n<=10^5

Output

一个非负整数表示答案,你需要将答案对23333333取模

Input示例

3

Output示例

2
分类讨论,
1 1 到根号n,前缀和优化
2 根号n到n, 最多只能选根号n个, 于是有
ff[q][j] = ff[p][j - m - 1] + ff[q][j - i])
ff[i][j] 代表从根号n+1到n共选了i个,体积为j, 种类是多少

#include<iostream>#include<cmath>#include<cstring>#define mem(x) (memset(x,0,sizeof(x)))using namespace std;const int LEN = 100000 + 5;const int mod = 23333333;int f[2][LEN];int ff[2][LEN];int main(void){    int n;    cin >> n;    int m = sqrt(n);    int p = 0, q = 1;    f[0][0] = 1;    for (int i = 1; i <= m; ++i,p^=1,q^=1)    {        mem(f[q]);        for (int j = 0; j < i; ++j)        {            int s = 0;            for (int k = 0; k *i + j <= n; ++k)            {                s = (s + f[p][k*i + j]) % mod;                f[q][k*i + j] = s;                if (k >= i)                    s = (s + mod - f[p][i*(k - i )+ j]) % mod;            }        }    }    int t = p,ans = f[t][n];    //cout << ans << endl;    p = 0, q = 1;    ff[0][0] = 1;    for (int i =1; i <= m; ++i,p^=1,q^=1)    {        mem(ff[q]);        for (int j = m+1; j <= n; ++j)        {                ff[q][j] = (ff[p][j - m - 1] + ff[q][j - i])%mod;        }        for (int j = 0; j <= n; ++j)            ans = (ans + (long long)f[t][j] * ff[q][n - j]) % mod;        //cout << ans << endl;    }    cout << ans << endl;    return 0;}

1 答案一
2 答案二
3 答案三

原创粉丝点击