题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2915
http://acm.hdu.edu.cn/showproblem.php?pid=2379
题目的意思就是给定一些单词,可以用这些单词的任意组合作为密码。求一个密码长度为l,恰好由k个给定的单词组成的种数。
是个动态规划的题目,题目很好理解,用dp[i][j]表示由i个单词组成长度为j的密码的种数,则dp[i+1][j+k]=dp[i][j]*cnt[k](1<k<10)则本题就比较简单了。
因为单词个数最大为5即L,密码长度最大为50即LEN,单词长度最大为10即K,所以时间复杂度为O(L*LEN*K)。cnt【k】表示长度为k的单词总共由多少个。
代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
using namespace std;
const int LEN=52;
const int N=7;
__int64 dp[N][LEN];
int cnt[11];
int main()
{
int t,m,n,q,i,k,j,l;
scanf("%d",&t);
string a;
while (t--)
{
scanf("%d%d%d",&m,&n,&q);
while (m--)
{
cin>>a;
cnt[a.length()]++;
}
memset(dp,0,sizeof(dp));
for (i=1;i<=10;i++)
{
dp[1][i]=cnt[i];
dp[i][i]=cnt[1];
}
for (i=0;i<5;i++)
{
for (k=0;k<=10;k++)
{
for (j=0;j<=LEN-k;j++)
{
dp[i+1][j+k]+=dp[i][j]*cnt[k];
}
}
}
while (q--)
{
scanf("%d",&l);
printf("%I64d\n",dp[n][l]);
}
}
return 0;
}