Just A String
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 643 Accepted Submission(s): 182
Problem Description
soda has a random string of length n which is generated by the following algorithm: each of n characters of the string is equiprobably chosen from the alphabet of size m.
For a string s, if we can reorder the letters in string s so as to get a palindrome, then we call s a good string.
soda wants to know the expected number of good substrings in the random string.
Input
There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:
The first line contains two integers $n and m (1 leq n,m leq 2000)$.
Output
For each case, if the expected number is E, a single integer denotes$ Edot mn mod 1000000007$.
Sample Input
3
2 2
3 2
10 3
Sample Output
10
40
1908021
Author
zimpha@zju
1 #include <iostream> 2 #include <algorithm> 3 #include <cstdio> 4 using namespace std; 5 const int maxn = 2002; 6 const int mod = 1000000007; 7 long long dp[maxn][maxn],PM[maxn]; 8 int main() { 9 PM[0] = dp[1][0] = 1; 10 int kase,n,m; 11 scanf("%d",&kase); 12 while(kase--) { 13 scanf("%d%d",&n,&m); 14 dp[1][1] = m; 15 for(int i = 1; i <= n; ++i) PM[i] = PM[i-1]*m%mod; 16 for(int i = 2; i <= n; ++i) { 17 for(int j = 0, k = min(i,m); j <= k; ++j) { 18 dp[i][j] = 0; 19 if(j) dp[i][j] += dp[i-1][j-1]*(m - j + 1); 20 if(j + 1 <= min(i - 1,k)) dp[i][j] += dp[i-1][j+1]*(j + 1); 21 dp[i][j] %= mod; 22 } 23 } 24 long long ret = 0; 25 for(int i = 1; i <= n; ++i) 26 ret += dp[i][i&1]*(n - i + 1)%mod*PM[n-i]%mod; 27 printf("%I64d ",ret%mod); 28 } 29 return 0; 30 }