您的位置:首页 > 产品设计 > UI/UE

UVA - 10689 Yet another Number Sequence 矩阵快速幂

2016-01-21 15:58 926 查看
[b] Yet another Number Sequence[/b]

Let’s define another number sequence, given by the following function:
f(0) = a
f(1) = b
f(n) = f(n − 1) + f(n − 2), n > 1
When a = 0 and b = 1, this sequence gives the Fibonacci Sequence. Changing the values of a and
b, you can get many different sequences. Given the values of a, b, you have to find the last m digits of
f(n).
[b]Input[/b]
The first line gives the number of test cases, which is less than 10001. Each test case consists of a
single line containing the integers a b n m. The values of a and b range in [0,100], value of n ranges in
[0,1000000000] and value of m ranges in [1,4].
[b]Output[/b]
For each test case, print the last m digits of f(n). However, you should NOT print any leading zero.
[b]Sample Input[/b]
4
0 1 11 3
0 1 42 4
0 1 22 4
0 1 21 4
[b]Sample Output[/b]
89
4296
7711
946

[b]题意:[/b]

给你 f[0],f[1] 分别为A,B求F
% (10^m)

[b]题解:[/b]

n有点大,矩阵快速幂

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std ;
typedef long long ll;

const int  N = 100000 + 10;
const int mod = 1e9 + 7;
const int M[55] = {1, 10, 100, 1000, 10000};
struct Matrix {
ll mat[2][2];
}U,F,L;
ll MOD;
Matrix multi (Matrix a, Matrix b) {
Matrix ans;
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
ans.mat[i][j] = 0;
for(int k = 0; k < 2; k++)
ans.mat[i][j] += a.mat[i][k] * b.mat[k][j];
ans.mat[i][j] %= MOD;
}
}
return ans;
}
ll a,b,m;
Matrix powss(ll n) {
Matrix ans = L,p = U;
while(n) {
if(n&1) ans = multi(p,ans);
n >>= 1;
p = multi(p,p);
}
return ans;
}
int main() {

int T;
scanf("%d",&T);
while(T--) {
ll n;
scanf("%lld%lld%lld%lld",&a,&b,&n,&m);
U = {1,1,1,0};
L = {b,0,a,0};
MOD = M[m];
Matrix ans = powss(n);
printf("%lld\n",ans.mat[1][0]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: