J - J - Birthday Party
Time limit : 1 s | Memory limit : 512 mb |
---|---|
Submitted : 53 | Accepted : 19 |
64bit Integer Format : %lld |
---|
Problem Description
Mr. Frog's birthday party will be held tomorrow. His friends will come to celebrate his birthday. He invited N friends(including himself) to come to his party. For some reason, he had not enough time to prepare for the party. He only cooked M(M<N) dishes. As a tradition, each dish should be placed in front of a person so that the number of dishes should be equal to the number of person who come to the party. It will be embarrassing if the number of dishes is not enough. So Mr. Frog planned to place the dishes in some ways so that the embarrassment will not be easy to find out.
The table is round and his friend will sit around the table together with him. If two dishes placed next to each other are same, it will be easy for his friends to find the embarrassment. Mr. Frog is wonder to know the number of ways to place the dishes. Certainly, the number of dishes placed on the table can be less than M. Please notice that the dishes will be placed on the table in front of each of his friends, which means the following two pictures shows different ways to place the dishes.

Input
First line is an integer T, which means the number of test cases.
The following T lines has T test cases. Each line has two integers, which indicates N and M.(4<=N<M<=100000)
Output
For each test case, output the case number and the number of ways Mr. frog can place the dishes. Since the number is too large, you should output the answer mod 100000007.
Sample Input
2
5 3
5 4
Sample Output
Case #1: 30
Case #2: 240
Hint
For the first case, the following ways are allowed(the first dish is next to the last dish to form a circle):
1-2-1-2-3 2-1-2-3-1 1-2-3-1-2 2-3-1-2-1 3-1-2-1-2
2-1-2-1-3 1-2-1-3-2 2-1-3-2-1 1-3-2-1-2 3-2-1-2-1
3-1-3-1-2 1-3-1-2-3 3-1-2-3-1 1-2-3-1-3 2-3-1-3-1
1-3-1-3-2 3-1-3-2-1 1-3-2-1-3 3-2-1-3-1 2-1-3-1-3
2-3-2-3-1 3-2-3-1-2 2-3-1-2-3 3-1-2-3-2 1-2-3-2-3
3-2-3-2-1 2-3-2-1-3 3-2-1-3-2 2-1-3-2-3 1-3-2-3-2
思路:dp[i][0]表示第i个座位与第1个座位菜式一样的方案数,dp[i][1]表示第i个座位与第1个座位菜式不一样的方案数,答案为dp[n][1]。
# include <bits/stdc++.h>
# define ll long long
using namespace std;
const int maxn = 1e5;
const int mod = 100000007;
ll dp[maxn+3][2];
int main()
{
int t, n, m, cas=1;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
dp[1][0] = m;
dp[1][1] = 0;
for(int i=2; i<=n; ++i)
{
dp[i][0] = dp[i-1][1];
dp[i][1] = (dp[i-1][0]*(m-1) + dp[i-1][1]*(m-2)) % mod;
}
printf("Case #%d: %lld\n",cas++, dp[n][1]);
}
return 0;
}