HOJ contests 15 J dp

版权声明:有错误欢迎大家指出。转载请注明出处~ https://blog.csdn.net/black_miracle/article/details/71640952

Birthday Party

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


题意:对于一个有n个位置的圆桌,有m种菜,要求每个位置都摆上菜,相邻位置不能有相同的菜,桌上的菜可以少于m种。
求有多少种不同的方案数,对答案mod100000007。


题解:定义dp[i][0]为和第一个不同的方案  dp[0][1]为和第一个相同的

dp[1][0]=0 dp[1][1]=m

dp[2][0]=m*(m-1)  dp[2][1]=0

dp[i][0]=dp[i][0]=dp[i-1][0]*(m-2)+dp[i-1][1]*(m-1)

dp[i][1]=dp[i-1][0]


答案就是dp[n][0]


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
ll f[100005][2];
int main(){
	int t,cas=1;
	scanf("%d",&t);
	while(t--){
		int i,n,m;
		scanf("%d%d",&n,&m);
		f[1][0]=0;
		f[1][1]=m;
		f[2][0]=m*(m-1)%100000007;
		f[2][1]=0;
		for(i=3;i<=n;i++){
			f[i][0]=(f[i-1][0]*(m-2)%100000007+f[i-1][1]*(m-1)%100000007)%100000007;
			f[i][1]=f[i-1][0]%100000007;
		}
		printf("Case #%d: %lld\n",cas++,f[n][0]);
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/black_miracle/article/details/71640952
今日推荐