1. 问题描述:
监狱有连续编号为 1 到 n 的 n 个房间,每个房间关押一个犯人。有 m 种宗教,每个犯人可能信仰其中一种。如果相邻房间的犯人信仰的宗教相同,就可能发生越狱。求有多少种状态可能发生越狱。
输入格式
共一行,包含两个整数 m 和 n。
输出格式
可能越狱的状态数,对 100003 取余。
数据范围
1 ≤ m ≤ 10 ^ 8,
1 ≤ n ≤ 10 ^ 12
输入样例:
2 3
输出样例:
6
样例解释
所有可能的 6 种状态为:(000)(001)(011)(100)(110)(111)。
来源:https://www.acwing.com/problem/content/description/1292/
2. 思路分析:
分析题目可以知道需要求解的是至少包含两个相同数字的情况但是直接求不好求解,其实我们可以反过来求解,先求解出所有的情况a,然后求解任何两个相邻的数字都不相邻的情况b,a - b就是答案,这使用到了正难则反的思想。m ^ n - m * (m - 1) ^ (n - 1)
3. 代码如下:
class Solution:
def quickPower(self, x: int, n: int, mod: int):
res = 1
while n > 0:
if n & 1:
res = res * x % mod
x = x * x % mod
n >>= 1
return res
def process(self):
m, n = map(int, input().split())
mod = 100003
print((self.quickPower(m, n, mod) - m * self.quickPower(m - 1, n - 1, mod) + mod) % mod)
if __name__ == '__main__':
Solution().process()