D - Plant CodeForces - 185A ——矩阵快速幂

Dwarfs have planted a very interesting plant, which is a triangle directed “upwards”. This plant has an amusing feature. After one year a triangle plant directed “upwards” divides into four triangle plants: three of them will point “upwards” and one will point “downwards”. After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process.

这里写图片描述
Help the dwarfs find out how many triangle plants that point “upwards” will be in n years.

Input
The first line contains a single integer n (0 ≤ n ≤ 1018) — the number of full years when the plant grew.

Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

Output
Print a single integer — the remainder of dividing the number of plants that will point “upwards” in n years by 1000000007 (109 + 7).

Examples
Input
1
Output
3
Input
2
Output
10
Note
The first test sample corresponds to the second triangle on the figure in the statement. The second test sample corresponds to the third one.

先要构造矩阵,不难看出它的关系是nextup=up*3+down,nextdown=down*3+up;
所以矩阵就是
( 3 1 1 3 ) X ( 1 0 0 0 )
矩阵我是用结构体来存,因为不知道数组怎么搞= =!

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const ll mod=1e9+7;
struct node
{
    ll mul[2][2];
    void init()
    {
        mul[0][0]=3;
        mul[0][1]=1;
        mul[1][0]=1;
        mul[1][1]=3;
    }
};
node calc(node a,node b)
{
    node ans;
    for(int i=0;i<=1;i++)
    {
        for(int j=0;j<=1;j++)
        {
            ans.mul[i][j]=0;
            for(int k=0;k<=1;k++)
            {
                ans.mul[i][j]=(ans.mul[i][j]+a.mul[i][k]*b.mul[k][j])%mod;
            }
        }
    }
    return ans;
}
ll qpow(ll b)
{
    node ret;
    ret.init();
    node sta;
    sta.mul[0][0]=1;
    sta.mul[0][1]=0;
    sta.mul[1][0]=0;
    sta.mul[1][1]=0;
    while(b)
    {
        if(b&1)
            sta=calc(sta,ret);
        ret=calc(ret,ret);
        b>>=1;
    }
    return sta.mul[0][0];
}
int main()
{
    ll n;
    scanf("%lld",&n);
    printf("%lld\n",qpow(n));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/tianyizhicheng/article/details/81569270