【题目】
Killer NamesTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1898 Accepted Submission(s): 924 Problem Description > Galen Marek, codenamed Starkiller, was a male Human apprentice of the Sith Lord Darth Vader. A powerful Force-user who lived during the era of the Galactic Empire, Marek originated from the Wookiee home planet of Kashyyyk as the sole offspring of two Jedi Knights—Mallie and Kento Marek—who deserted the Jedi Order during the Clone Wars. Following the death of his mother, the young Marek's father was killed in battle by Darth Vader. Though only a child, Marek possessed an exceptionally strong connection to the Force that the Dark Lord of the Sith sought to exploit. Input The First line of the input contains an integer T (T≤10 ), denoting the number of test cases. Output For each test case, output one line containing the maximum number of clones Vader can create. Sample Input 2 3 2 2 3 Sample Output 2 18 |
【题解】
题意:给定m种不同字母,要求从m种字母中选出并组成合法名字,当任意字母不同时出现在姓和名中时称这个名字是合法的,姓和名的长度均为n,问最多可以组成多少个合法的名字。
思路:相当于涂色,给定m种颜色,为两个长度为n的单元格涂色,要求两个区域没有共同的颜色。这个题的方法就是先考虑姓,得到长度为n的分别用了j=1到m种颜色的方案数,那么对于名,就是(m-j)^n,即剩下的颜色填到n个格子的方案数。
dp[i][j]表示长度为i,用到j种颜色的情况数,显然dp[1][1]=m,状态转移方程为:dp[i][j]=dp[i-1][j]*j+dp[i-1][j-1]*(m-(j-1))。
长度为i用到j种颜色的数目=长度为i-1用到j种颜色的数目*j种颜色(第i个格是j种颜色中的一种)+长度为i-1用到j-1种颜色*(m-(j-1))种颜色(第i个格用的是剩下的m-(j-1)种颜色)。
【代码】
#include<stdio.h>
typedef long long ll;
const ll mod=1e9+7;
ll pow(ll x,ll n)
{
ll res=1;
while(n>0)
{
if(n&1) res=res*x%mod;
x=x*x%mod;
n>>=1;
}
return res;
}
ll dp[2005][2005]; //表示当长度为i时使用j种颜色的情况数目
main()
{
int T,n,m; scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
dp[1][1]=m;
for(int i=2;i<=n;i++)
for(int j=1;j<=i&&j<=m;j++)
dp[i][j]=dp[i-1][j]*j%mod+dp[i-1][j-1]*(m-(j-1))%mod;
ll ans=0;
for(int j=1;j<=m;j++)
ans=(ans+dp[n][j]*pow(m-j,n)%mod)%mod;
printf("%lld\n",ans);
}
}