这道题是我们周赛的第一场的一道题,一道经典的DP问题。
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.
这道题目就是题意有点难理解,讲解一下题意:题目给我们N个程序员,M行需要写的代码,B个最多能错的BUG,还有因为数据过大需要取余的模Mod,下一行是每个程序员写每一行代码会写出的Bug。我们要的答案就是利用这些个程序员写B个Bug以内的M行代码,能有多少中方法,结果余Mod。
思路:这是一道完全背包的问题,我们从第一个程序员开始考虑,取一个、两个、......、M个,然后我们还要考虑到达这行会写出的Bug。那么考虑到多个程序员之后,就需要考虑写到某一行、以及对应行时产生的Bug数的情况。得到状态转移方程:dp[j][k]=(dp[j][k]+dp[j-1][k-a[i]])%Mod。
完整代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
int dp[505][505]; //分别记录此时写到第几行和错的题
int N,M,B,Mod; //人数、代码行数、bug上限、取模
int a[505]; //每个人每行错误代码数
int ans=0;
int main()
{
while(scanf("%d%d%d%d",&N, &M, &B, &Mod)!=EOF)
{
ans=0;
memset(a, 0, sizeof(a));
memset(dp, 0, sizeof(dp));
for(int i=1; i<=N; i++)
{
scanf("%d",&a[i]);
}
dp[0][0]=1;
for(int i=1; i<=N; i++)
{
for(int j=1; j<=M; j++)
{
for(int k=a[i]; k<=B; k++)
{
dp[j][k]=(dp[j][k]+dp[j-1][k-a[i]])%Mod;
}
}
}
for(int i=0; i<=B; i++)
{
ans+=dp[M][i];
ans%=Mod;
}
printf("%d\n",ans);
}
return 0;
}