CodeForces450B Jzzhu and Sequences (矩阵快速幂)
来源:互联网 发布:软件性质 编辑:程序博客网 时间:2024/06/11 13:45
Jzzhu has invented a kind of sequences, they meet the following property:
You are given x and y, please calculate fn modulo 1000000007 (109 + 7).
The first line contains two integers x and y (|x|, |y| ≤ 109). The second line contains a single integer n (1 ≤ n ≤ 2·109).
Output a single integer representing fn modulo 1000000007 (109 + 7).
2 33
1
0 -12
1000000006
In the first sample, f2 = f1 + f3, 3 = 2 + f3, f3 = 1.
In the second sample, f2 = - 1; - 1 modulo (109 + 7) equals (109 + 6).
题目大意:输入x,y,n,f(1) = x, f(2) = y,求f(n);
思路:从题意可知:f(n) = f(n-1) + f(n+1), 即f(n+1) = f(n) - f(n-1)....看上去是不是特别想斐波那契数列。。。。可以求得系数矩阵 A = {{1,-1}{1,0}},所以可以通过矩阵快速幂来求出f[n]。
x[1] = {f[2],-f[1]},所以x[n] = {f[n+1],-f[n]},,因为要求f[n]的值,所以我们要求的是x[n-1],即A^(n-2) * X1 = X(n-1),所以calcu(n-2)。
代码如下:
#include <bits/stdc++.h>using namespace std;#define ll long longconst ll mod = 1e9+7;ll x,y,n;struct Matrix{ll a[3][3];}ori,res;void Init(){ori.a[0][0] = ori.a[1][0] = 1;ori.a[0][1] = -1;ori.a[1][1] = 0;memset(res.a,0,sizeof(res));for(int i = 0; i < 2; i ++) res.a[i][i] = 1;}Matrix multiply(Matrix x, Matrix y){Matrix temp;memset(temp.a,0,sizeof(temp.a));for(int i = 0; i < 2; i ++){for(int j = 0; j < 2; j ++){for(int k = 0; k < 2; k ++){temp.a[i][j] += (x.a[i][k] * y.a[k][j] % mod);temp.a[i][j] %= mod;}}}return temp;}void calcu(int n){Matrix temp;while(n){if(n & 1) res = multiply(res,ori);n >>= 1;ori = multiply(ori,ori);}memset(temp.a,0,sizeof(temp.a));temp.a[0][0] = y; temp.a[1][0] = x;res = multiply(res,temp);printf("%lld\n",(res.a[0][0] + mod) % mod);}int main(){while(~scanf("%lld%lld%lld",&x,&y,&n)){Init();if(n == 1) printf("%lld\n",(x + mod) % mod);else if(n == 2) printf("%lld\n",(y + mod) % mod);else calcu(n-2);//f(n+1) = f(n) -f(n-1),}return 0;}
- CodeForces450B Jzzhu and Sequences (矩阵快速幂)
- Jzzhu and Sequences 【矩阵快速幂】
- Jzzhu and Sequences - CF 450B 矩阵快速幂版
- Codeforces 450B Jzzhu and Sequences(矩阵快速幂)
- Codeforces #257B Jzzhu and Sequences(矩阵快速幂)
- CF 450 B Jzzhu and Sequences(矩阵快速幂)
- hdu-4686 Jzzhu and Sequences 【矩阵快速幂】
- Codeforces 450B Jzzhu and Sequences(矩阵快速幂)
- Codeforces 450B-Jzzhu and Sequences (矩阵快速幂)
- codeforces 450-B Jzzhu and Sequences 矩阵快速幂
- Codeforces 450B Jzzhu and Sequences(矩阵快速幂)
- Codeforces Round #257 (Div. 2) 450B - Jzzhu and Sequences(循环节或矩阵快速幂)
- Codeforces Round #257(Div. 2) B. Jzzhu and Sequences(矩阵快速幂)
- 【矩阵快速幂 】Codeforces 450B - Jzzhu and Sequences (公式转化)
- B. Jzzhu and Sequences
- Jzzhu and Sequences
- B. Jzzhu and Sequences
- cf450B. Jzzhu and Sequences
- Kettle Sql Server插入语句和执行语句生成方法
- (一)OpenCV3.3.0安装配置(opencv3.3.0+VS2015社区版+64位win7)(转)
- 简单的js网页应用(事件与事件处理的响应)
- hdu2018:Shape of HDU
- ACM第二次比赛题目及标准程序(基础水题)
- CodeForces450B Jzzhu and Sequences (矩阵快速幂)
- canal简介
- Hbase底层数据结构
- hdu-6098-Inversion
- mybatis解决数据库表列明与实体不一致问题
- ubuntu14.04源码安装tensorflow
- spring mvc基础篇(六):Spring mvc之拦截器
- Java知识(访问修饰符、方法重写和方法重载的区别以及java抽象)
- 2017 Multi-University Training Contest