Codeforces Round #118 (Div. 1) A 矩阵快速幂

A. Plant
 

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 %I64dspecifier.

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
Copy
1
output
Copy
3
input
Copy
2
output
Copy
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.

 

一个向上的三角形会变成三个向上的三角形和一个向下的三角形。

一个向下的三角形会变成三个向下的三角形和一个向上的三角形。

设当前有Xn个向上的三角形,Yn个向下的三角形。

那个优

Xn      3     1   Xn-1 

    =

Yn          1      3     Yn-1

 

有公式就好写代码了。

 1 // an = 2*a(n-1)+4^(n-1)
 2 // 设向上的有Xn,向下有Yn
 3 // 那么有:
 4 // Xn = 3*X(n-1) + Y(n-1)
 5 // Yn = X(n-1) + 3*Y(n-1)
 6 #include <bits/stdc++.h>
 7 #define ll long long
 8 using namespace std;
 9 const ll mod = 1000000007;
10 struct mat{
11     ll m[2][2];
12     mat(){
13         memset(m, 0, sizeof(m));
14     }
15 };
16 
17 mat mul(mat &A, mat &B) {
18     mat C;
19     for(int i = 0; i < 2; i++) {
20         for(int j = 0; j < 2; j ++) {
21             for(int k = 0; k < 2; k ++) {
22                 C.m[i][j] = (C.m[i][j] + A.m[i][k]*B.m[k][j]) % mod;
23             }
24         }
25     }
26     return C;
27 }
28 
29 mat pow(mat A, ll n) {
30     mat B;
31     for(int i = 0; i < 2; i ++) B.m[i][i] = 1;
32     while(n) {
33         if(n&1) B = mul(B, A);
34         A = mul(A, A);
35         n >>= 1;
36     }
37     return B;
38 }
39 int main() {
40     ll n;
41     cin >> n;
42     mat A;
43     A.m[0][0] = A.m[1][1] = 3;
44     A.m[0][1] = A.m[1][0] = 1;
45     A = pow(A, n);
46     cout << A.m[0][0]<< endl;
47     return 0;
48 }

 

转载于:https://www.cnblogs.com/xingkongyihao/p/9000087.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值