Mr.BG Hates Palindrome (SPOJ - GOC11B)

Mr.BG is very busy person. So you have been given enough time (1000 milliseconds) to help him.


Mr. BG has a bag of marbles with different alphabets written on them. And he has become busy on playing with these marbles by putting them in N boxes placed in a row. There are exactly M distinct type of marbles, N of each type.

Now he puts only N marbles (out of M*N) in N boxes, one by one and upon completion he writes down the letters on the marbles on a paper to form a string. As Mr.BG hates palindrome strings (strings which read same from both sides e.g. MADAM), he erases palindrome string from the paper as soon as he finds one.

Now he is wondering how many different strings he might get on his paper if he could try all possible combination of putting the marbles in the boxes. So you have to help him by answering. As there could be many strings so print it modulo 1,000,000,007.

Input

Input starts with an integer TC(<=10), denoting the number of test cases. Each case starts with two non negative integers N(<=100000) and M(<=26) as described above.

Output

For each case, print the case number and total number of strings written on the paper modulo 1000000007.

Example

Input:
2
2 2
2 3
Output:
Case 1: 2 
Case 2: 6

题意:从m个不同字符中选取字符构成一个长度为n的新字符串,让你计算一共有多少个不同的非回文串。

这题其实是一个比较水的题,但还是要注意几个细节:

<1> : 快速幂

<2> : 减法的求余公式。

<3> : 数的范围。

解题思路:
符合要求的数量 = 总数量 - 回文串。

结果为: pow(m,n) - pow( m,(n+1)/2 );

代码如下:

#include<cstdio>
using namespace std;
const int maxn = 1000000007;
long long pp(long long a,long long b)
{
	a = a%maxn;
	long long num = 1;
	while(b)
	{
		if(b&1) num =  num*a%maxn;
		a = a*a%maxn;
		b >>= 1;
	}
	return num;
}
int main()
{
	int T;
	long long n,m;
	long long sum;
	scanf("%d" ,&T);
	for(int i=1; i<=T; i++)
	{
	   scanf("%lld %lld", &n, &m);
	   printf("Case %d: ",i); 
	   if(n%2==0)
	   sum = (pp(m,n) - pp(m,n/2) +maxn) % maxn;
	   else
	   sum = (pp(m,n) - pp(m,n/2+1) +maxn)% maxn;
	   printf("%lld\n", sum);
	}
	return 0;	
} 

水波。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值