标签:+= end com bsp cout input queue als mod
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).
Input
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
Output a single integer representing fn modulo 1000000007 (109?+?7).
2 3
3
1
0 -1
2
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).
使用矩阵快速幂,构造2*2矩阵从左到右从上到下为 1,1,-1,0。代码如下:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <utility>
#define ll long long
using namespace std ;
const ll MOD = 1e9+7 ;
const int maxn = 2 ;
struct matrix{
int m[maxn][maxn] ;
}mat ;
matrix operator *(matrix a , matrix b){
matrix res ;
for ( int i = 0 ; i < maxn ; i ++ ){
for ( int j = 0 ; j < maxn ; j ++ ){
ll temp = 0 ;
for ( int k = 0 ; k < maxn ; k ++ ){
temp += (a.m[i][k] % MOD * b.m[k][j] % MOD) % MOD ;
}
res.m[i][j] = temp % MOD ;
}
}
return res ;
}
void init(){
for ( int i = 0 ; i < maxn ; i ++ ){
mat.m[i][i] = 1 ;
}
return ;
}
matrix quick_pow(matrix a, ll n){
matrix ans = mat ;
while (n){
if (n & 1){
ans = ans * a ;
}
a = a * a ;
n >>= 1 ;
}
return ans ;
}
int main(){
ll x , y , n ;
while ( cin >> x >> y >> n ){
if ( n == 1 ){
cout << (x % MOD + MOD) % MOD << endl ;
}else if ( n == 2 ){
cout << (y % MOD + MOD) % MOD << endl ;
}else{
init() ;
matrix temp ;
temp.m[0][0] = 1 , temp.m[0][1] = 1 ;
temp.m[1][0] = -1 , temp.m[1][1] = 0 ;
temp = quick_pow(temp , n - 2) ;
matrix ans ;
ans.m[0][0] = y , ans.m[0][1] = x ;
ans = ans * temp ;
cout << (ans.m[0][0] % MOD + MOD) % MOD << endl ;
}
}
return 0 ;
}
Codeforces Round 450 Div2 B.Jzzhu and Sequences
标签:+= end com bsp cout input queue als mod
原文地址:https://www.cnblogs.com/Cantredo/p/10041712.html