Link: https://ac.nowcoder.com/acm/problem/14718
Source: Niuke
Title description
There are m colors and n grids, it is necessary to calculate the number of solutions of the same color in two adjacent grids
answer
First of all, I found that it is not easy to calculate directly, so consider the
total number of plans: mnm^nmn
consider that the first position hasmmm kinds of placement methods, the second position in order to keep the color of adjacent grids different, onlym − 1 m-1m−1 method, and so on,nnThere are onlym − 1 m-1 in n positionsm−1 method of placement The
number of schemes with different adjacent grid colors:m × (m − 1) (n − 1) m\times(m-1)^{(n-1)}m×(m−1)(n−1)
Knowledge integration
Fast power
When my a, ba, ba,When b is greater than my modulus, foraaa modulo andbbb Euler power
Code
#include<iostream>
using namespace std;
#define mod 1000000007
typedef long long ll;
const int N = 1e6 + 10;
ll qpow(ll a, ll b, ll p) {
//当我的a, b大于我的p时
//取模并欧拉降幂
a %= p, b %= p - 1;
ll res = 1;
while (b) {
if (b & 1) {
res = (res * a) % p;
}
a = (a * a) % p;
b >>= 1;
}
return res;
}
int main() {
ll n, m;
cin >> n >> m;
ll ans = qpow(m, n, mod);
//注意数据范围和取模技巧
ans = (ans - m % mod * qpow(m - 1, n - 1, mod) % mod);
//把答案映射到正整数
ans = (ans % mod + mod) % mod;
cout << ans << endl;
return 0;
}