1598-TomCat的环(数学+快速幂) ZCMU

Description

TomCat有一个环(如图)有N个单元,并且有4中颜色。他希望把环的每一个单元格都染上颜色,但是相邻的两个单元格颜色不能相同。他想知道一共有几种染色方法

Input

输入单元格数N,N<=100000。

Output

输出染色总数对1000000007取余的结果。

Sample Input

1

2

Sample Output

4

12

解析

对分成了n块的环,涂m种颜色,相邻两个不能为同种色的问题,涂色方案数为 (m-1)^n+(-1)^n*(m-1)  (m>=2&&n>=2)

代码

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod=1000000007;
//快速幂取模算法
ll quick_pow(ll a,ll b)
{
    ll ret=1;
    while(b>0)
    {
        if(b%2==1)
          ret=ret*a%mod;
        a=a*a%mod;
        b=b/2;
    }
    return ret;
}
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        if(n==1) printf("4\n");
        else
        {
            ll ans=quick_pow(3,n)%mod;
            if(n%2==1)
                ans-=3;
            else
                ans+=3;
            printf("%lld\n",ans);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ZCMU_2024/article/details/81381682