BZOJ 1008 越狱

题目代号:BZOJ 1008

题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1008

Problem 1008. -- [HNOI2008]越狱

1008: [HNOI2008]越狱

Time Limit: 1 Sec  Memory Limit: 162 MB
Submit: 9540  Solved: 4128

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=(mn+m*(m-1)n-1)%mod。可能有负数,所以要消除影响得到ans=(((mn+m*(m-1)n-1)%mod)+mod)%mod;

快速幂可以将O(n2)转变成O(logn)很实用。

AC代码:

# include <iostream>
# include <cstring>
# include <cstdlib>
# include <cstdio>
# include <cmath>
# include <map>
# include <queue>
# include <stack>
# include <vector>
# include <fstream>
# include <algorithm>
using namespace std;
# define bug puts("")
# define pi acos(-1.0)
# define mem(a,b) memset(a,b,sizeof(a))
# define IOS ios::sync_with_stdio(false)
# define FO(i,n,a) for(int i=n; i>=n; --i)
# define FOR(i,a,n) for(int i=a; i<=n; ++i)
typedef unsigned long long ULL;
typedef long long LL;
inline int Scan() {
    int x=0,f=1; char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-') f=-1; ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0'; ch=getchar();}
    return x*f;
}
///coding...................................

LL mod_pow(LL x,LL n,LL mod) {
    LL res=1;
    while(n>0) {
        if(n&1)res=res*x%mod;
        x=x*x%mod;
        n>>=1;
    }
    return res;
}

int main()
{
#ifdef FLAG
    freopen("in.txt","r",stdin);
#endif /// FLAG
    LL m,n,ans,mod=100003;
    while(~scanf("%lld%lld",&m,&n)) {
        LL t1=mod_pow(m,n,mod);
        LL t2=m*mod_pow(m-1,n-1,mod);
        ans=((t1-t2)%mod+mod)%mod;
        cout<<ans<<endl;
    }
    return 0;
}

 

posted @ 2017-07-31 10:27  韵祈  阅读(86)  评论(0编辑  收藏