HYSBZ 1008 越狱 快速幂取模

来源:互联网 发布:淘宝全球购认证商家 编辑:程序博客网 时间:2024/06/01 10:33

原题: http://www.lydsy.com/JudgeOnline/problem.php?id=1008

题目:

1008: [HNOI2008]越狱

Time Limit: 1 Sec Memory Limit: 162 MB
Submit: 5454 Solved: 2335
[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)

思路:

相邻相同就越狱,相邻的情况太多了,所以我们找相邻不同的情况。
对于n个人m种信仰,除了第一个人可以选m种,后面的每个人为了保证不和前面重复,只能选m-1种,所以一共就有m*(m-1)^(n-1)种不重复的情况,不考虑信仰重复问题我们共有m^n种情况么,这里做差就能求出越狱的情况。
注意:由于数据量大,所以对于每次计算的数据都要取模一次。
选c++记得用%lld读取。

代码:

#include <iostream>#include"cstdio"#include"string.h"using namespace std;typedef long long int lint;const lint mod=100003;lint func(lint x,lint y)   //a^b{    if(y==0)    return 1;    lint temp;    temp=func(x, y /2);    temp=temp%mod;    temp=temp*temp;    if(y%2==1)  temp=temp*x;    temp=temp%mod;    return temp;}int main(){    //freopen("in.txt","r",stdin);    lint n,m;    while(scanf("%lld %lld",&m,&n)!=EOF)    {        lint ans=(func(m,n)%mod+mod-(m*func(m-1,n-1))%mod)%mod;        printf("%lld\n",ans);    }    return 0;}
0 0
原创粉丝点击