1008: [HNOI2008]越狱(计数问题)

时间:2023-01-31 00:54:56

1008: [HNOI2008]越狱

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

 

 

分析

正着想不好想,反过来想,求不发生越狱的方案数,用总方案数减去即可。

总方案数$=m^n$,每个房间都有m中选择

不发生越狱的方案数$=m*(m-1)^{n-1}$,第一个房间有m中选择,因为第二个不能和第一个相同,所以有m-1个选择,第3,4...n个房间都是这样。

code

1008: [HNOI2008]越狱(计数问题)1008: [HNOI2008]越狱(计数问题)
 1 #include<cstdio>
2 #include<iostream>
3
4 using namespace std;
5 typedef long long LL;
6 const LL mod = 100003;
7
8 LL ksm(LL a,LL b) {
9 LL ret = 1;
10 while (b) {
11 if (b & 1) ret = (ret * a) % mod;
12 a = (a * a) % mod;
13 b >>= 1;
14 }
15 return ret % mod;
16 }
17 int main() {
18 LL m,n;
19 cin >> m >> n;
20 cout << ( (ksm(m,n) - m*ksm(m-1,n-1)%mod + mod) % mod); //-在m*ksm(..)需要mod
21 return 0;
22 }
View Code