Programmers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly ai bugs in every line of code that he writes.
Let's call a sequence of non-negative integers v1, v2, ..., vn a plan, if v1 + v2 + ... + vn = m. The programmers follow the plan like that: in the beginning the first programmer writes the first v1 lines of the given task, then the second programmer writes v2 more lines of the given task, and so on. In the end, the last programmer writes the remaining lines of the code. Let's call a plan good, if all the written lines of the task contain at most b bugs in total.
Your task is to determine how many distinct good plans are there. As the number of plans can be large, print the remainder of this number modulo given positive integer mod.
The first line contains four integers n, m, b, mod (1 ≤ n, m ≤ 500, 0 ≤ b ≤ 500; 1 ≤ mod ≤ 109 + 7) — the number of programmers, the number of lines of code in the task, the maximum total number of bugs respectively and the modulo you should use when printing the answer.
The next line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of bugs per line for each programmer.
Print a single integer — the answer to the problem modulo mod.
3 3 3 100 1 1 1
10
3 6 5 1000000007 1 2 3
0
3 5 6 11 1 2 1
0
【题意】给你n个一行代码,第 i 代码写的时候会产生 ai 个bug,要写 m 行,总的bug不能超过 b 个,问有多少种方案,对mod取模。
【解题思路】典型的背包问题,dp[i][j][k] = (dp[i-1][j][k] + dp[i][j-1][k-a[i]]) % mod; 表示不选第 i 个的话就有 dp[i-1][j][k], 选第 i 个就有 dp[i][j-1][k-a[i]]种方案。滚动数组节省空间。
【AC代码】#include <stdio.h> #include <string> #include <vector> #include <queue> #include <algorithm> #include <iostream> #include <string.h> using namespace std; int dp[2][510][510],a[510]; int n,m,b,mod; int main() { scanf("%d%d%d%d",&n,&m,&b,&mod); for(int i=1; i<=n; i++) scanf("%d",&a[i]); dp[0][0][0] = 1; int cur = 1,last = 0; for(int i=1; i<=n; i++) { for(int j=0; j<=m; j++) { for(int k=b; k>=a[i]; k--) if(j==0) dp[cur][j][k] = dp[last][j][k]; else dp[cur][j][k] = (dp[last][j][k] + dp[cur][j-1][k-a[i]])%mod; for(int k=a[i]-1; k>=0; k--) dp[cur][j][k] = dp[last][j][k];//用上一个没更新到的状态更新当前状态 } cur ^= 1; last ^= 1; } int ans = 0; for(int i=0; i<=b; i++) { ans = (ans+dp[last][m][i])%mod; } printf("%d\n",ans); return 0; }