BZOJ-1008 越狱 数论快速幂
1008: [HNOI2008]越狱
Time Limit: 1 Sec Memory Limit: 162 MB
Submit: 6192 Solved: 2636
[Submit][Status][Discuss]
Description
监狱有连续编号为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)
感觉没什么好说的,找出公式后,快速幂求值,%%%之后即可
公式为:ans=M^N-M*(M-1)^(N-1)
代码:
#include<iostream>
#include<cstdio>
using namespace std;
int qpow(long long m,long long n,long long k)
{
int b = 1;
while (n > 0)
{
if (n & 1)
b = (b*m)%k;
n = n >> 1 ;
m = (m*m)%k;
}
return b;
}
int main()
{
long long n=0,m=0;
scanf("%lld%lld",&m,&n);
long long ans=1;
ans=(qpow(m,n,100003)-m*qpow(m-1,n-1,100003)%100003+100003)%100003;
printf("%lld",ans);
return 0;
}
——It's a lonely path. Don't make it any lonelier than it has to be.