越狱(快速幂)

监狱有连续编号为1...N的N个房间,每个房间关押一个犯人,有M种宗教,每个犯人可能信仰其中一种。如果
相邻房间的犯人的宗教相同,就可能发生越狱,求有多少种状态可能发生越狱

Input

  输入两个整数M,N.1<=M<=10^8,1<=N<=10^12

Output

  可能越狱的状态数,模100003取余

Sample Input

2 3

Sample Output

6

Hint

6种状态为(000)(001)(011)(100)(110)(111)

个人心得:根据推导,就可以轻松得出不能出狱的情况这是只要将所有情况减去不能出狱的情况就好了,

m的n次幂m(m1)的n1次幂。

此时朴素算法会超时,所以必须要用到快速幂的思想,快速幂随笔里面已经涉及,去看就好了,不多说,代码附上

 

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<iostream>
 4 #include<algorithm>
 5 #include<utility>
 6 #include<queue>
 7 #include<set>
 8 using namespace std;
 9 #define k 100003
10 long long  n,m;
11 long long ksm(long long n,long long m)
12 {
13     long long s=1;
14     while(m)
15     {
16         if(m&1) s=((s%k)*(n%k))%k;
17         n=((n%k)*(n%k))%k;
18         m>>=1;
19     }
20  return s;
21 
22 
23 }
24 int main()
25 {
26     cin>>m>>n;
27     printf("%lld",((ksm(m,n)-(m%k*ksm(m-1,n-1))%k)%k+k)%k);
28     return 0;
29 
30 
31 }

 

posted @ 2017-08-02 10:40  余生漫漫浪  阅读(332)  评论(0编辑  收藏  举报