UVA - 10689 —— Yet another Number Sequence —— quickpow_Mat


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 andb, you can get many different sequences. Given the values of a, b, you have to find the last m digits off(n).

Input   The first line gives the number of test cases, which is less than 10001. Each test case consists of asingle 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].

Output   For each test case, print the last m digits of f(n).

However, you should NOT print any leading zero.

Sample Input  

4

0 1 11 3

0 1 42 4

0 1 22 4

0 1 21 4

Sample Output

89

4296

7711

946


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <map>
#include <sstream>
#include <queue>
#include <stack>
#include <vector>
using namespace std;

#define INF 0x3f3f3f3f
#define Mem(a,x) memset(a,x,sizeof(x))
#define For(i,a,b) for(int i = a; i<b; i++)
#define ll long long
#define MAX_N 100010

typedef vector<int> vec;
typedef vector<vec> mat;
int m;
int mod[4] = {10,100,1000,10000};
mat mul(mat &A,mat &B)
{
    mat C(A.size(),vec(B[0].size()));
    for(int i = 0; i<A.size(); i++)
    {
        for(int k = 0; k<B.size(); k++)
        {
            for(int j = 0; j<B[0].size(); j++)
            {
                C[i][j] = C[i][j] + A[i][k]*B[k][j];
                C[i][j] %= mod[m-1];
            }
        }
    }
    return C;
}
mat pow(mat A,ll n)
{
    mat B(A.size(),vec(A.size()));
    for(int i = 0; i<A.size(); i++)
        B[i][i] = 1;
    while(n > 0)
    {
        if(n & 1) B = mul(B,A);
        A = mul(A,A);
        n >>= 1;
    }
    return B;
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int x[10];
        Mem(x,0);
        int a,b;
        ll n;
        scanf("%d%d%lld%d",&a,&b,&n,&m);
        mat A(2,vec(2));
        A[0][0] = 1,A[0][1] = 1;
        A[1][0] = 1,A[1][1] = 0;
        A = pow(A,n);
        mat ans(2,vec(1));
        ans[0][0] = b,ans[1][0] = a;
        ans = mul(A,ans);
        printf("%d\n",ans[1][0]);
    }
    return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章