CRCLE_UI - Colorful Circle (EASY)

no tags 

------------------------
I take this problem from my midterm exam today, because for me and some of my friends it's interesting, so I decided to translated this problem into English and upload this problem to SPOJ. See the original problem in Indonesian language here.
------------------------ 

Given N sectors where 1<N<101000, from a circle that sown in the picture below:

circle

We will color each sector with K different colors, where 2<K<101000 such that each sector colored with one color and each adjacent sector must have different color. Your task is to count how many ways to color all that sectors.

Input

First line, there is a number T(0<T<1000) denoting number of test cases, then T lines follow.
each line containing two integers: N and K separated by a space.

Output

For each test case, output number of ways to color the circle, since the number can be too large, take modulo 109+7.

Example

Input:
2
2 3
3 3

Output:
6
6

Explanation:

For the first case, we have two sectors and three colors, here is all possibilities:

2 sectors 3 colors

For second test case, we have three sector and three colors, here is all possibilities:

3 sectors 3 colors

 

Time limit set so that ~128 Bytes of python 3 code can get accepted, also my C top speed program AC in 0.12s
Have fun :) 

 

See also: Another problem added by Tjandra Satria Gunawan


hide comments
Aditya Pande: 2012-12-31 08:58:37

should O(log(n)) pass in PYTHON 2.7

getting TLE....
is it formula based?

Ans: Yes, this problem is formula based, and ~128B of python cede CAN get accepted.. Be careful using mod operation.. it can slow down your code..

Last edit: 2012-12-31 09:37:22
Francky: 2012-11-16 08:29:50

It is not easy, xor we have the same definition of easy. ;-)
My kind of problem.
Note that : here the simple python3 code is faster than the python2 equivalent. (and I found some strange thing : usual speed tricks give slow code !!! Curious !!!)

Ans: Maybe this strange thing caused by my 'random' test data is not good(?) And congratulations you write a fastest C code :-)

Last edit: 2012-11-19 10:08:58
(Tjandra Satria Gunawan)(曾毅昆): 2012-11-15 03:44:37

Yes, actually to solve this problem we need clever implementation of mod operation ;-)
@Mitch Schwartz: Congratulations, you are the first solver :-D

Mitch Schwartz: 2012-11-15 01:52:53

Haha, the time limit is not very codegolf-friendly.


Added by:Tjandra Satria Gunawan
Date:2012-11-14
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64
Resource:Discrete Math II, Midterm exam, question number 4, University of Indonesia, 14 November 2012 | Translated by: Tjandra