Niu Ke—Happy Brushing
Topic link: Happy painting
Title
There are n grids and m colors. It is necessary to find out the matching number of two adjacent grids with the same color.
Problem-solving ideas
To understand how many coating methods there are, it is obviously mnm^{n}mn , then as long as you find all the coating methods with different adjacent colors, you can show that there are two adjacent grids with the same color.
How to express the color of any adjacent grid? It is very simple that you can choose any color for the first grid, and if the color of the second grid is different from that of the previous grid, there are only (m-1) colors to choose from, and so on, a total of n *(m − 1 ) n − 1 (m-1)^{n-1}(m−1)n − 1 coating method.
Then you can use fast power to calculatemnm^{n}mn, ( m − 1 ) n − 1 (m-1)^{n-1} (m−1)n − 1 .
Upload code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod = 1000000007;
ll fastpow(ll a , ll n){
ll res = 1, base = a % mod;//这里一定要取mod因为m可能会大于mod
while(n){
if(n & 1)
res = (res * base) % mod;
base = (base * base) % mod;
n >>= 1;
}
return res;
}
int main(){
ll n, m, x, y, ans;
cin >> n >> m;
x = fastpow(m, n) % mod;
y = (m % mod * fastpow(m - 1, n - 1)) % mod;
if(x - y > 0)//因为取mod了,所以有可能x < y ,小于的话加一个mod就ok
ans = (x - y) % mod;
else
ans = (x - y + mod) % mod;
cout << ans << endl;
return 0;
}