版权声明:本文为博主原创,未经博主允许不得转载 https://blog.csdn.net/Sherry_Yue/article/details/87431630
Applese 涂颜色(C++)
题目描述
精通程序设计的 Applese 叕写了一个游戏。
在这个游戏中,有一个 n 行 m 列的方阵。现在它要为这个方阵涂上黑白两种颜色。规定左右相邻两格的颜色不能相同。请你帮它统计一下有多少种涂色的方法。由于答案很大,你需要将答案对
取模。
输入描述:
仅一行两个正整数 n, m,表示方阵的大小。
输出描述:
输出一个正整数,表示方案数对
取模。
示例1
输入
1 1
输出
2
示例2
输入
2 2
输出
4
备注:
题目思路:
一个比较显然的结论是,对于每一行,有 2 种涂色方法。即当每一行第一个颜色确定后,后面的颜色均为已知。
所以,答案就是
注意本题的 n 为高精度(因为n实在是太大了),需要使用指数循环节降幂或者十进制快速幂。
快速幂的推到和代码参考(十分详细)https://blog.csdn.net/scar_lyw/article/details/70169737
解题代码:
#include <iostream>
#include <cstring>
using namespace std;
#define LL long long
const LL mod = 1e9+7;
LL ksm(LL a,LL b)//快速幂
{
LL ans = 1;
a %= mod;
while( b>0 )
{
if( b&1 ) ans = (ans*a)%mod;
b >>= 1;//位运算,右移1位,相当于除以2
a = (a*a)%mod;
}
return ans;
}
int main()
{
ios::sync_with_stdio(false);//加速
string n,m;
cin >> n >> m;
int len = n.length();//长度
LL k = 0;
for(int i=0;i<len;++i) k = ( k*10 + ( n[i]-'0' ) ) % ( mod-1 );
cout << ksm(2,k) << endl;
}