nyoj301——递推求值

来源:互联网 发布:php高并发秒杀 实例 编辑:程序博客网 时间:2024/04/24 15:08

nyoj301递推求值:http://acm.nyist.net/JudgeOnline/problem.php?pid=301

用矩阵快速幂求解

递推求值

时间限制:1000 ms  |  内存限制:65535 KB
难度:4
描述

给你一个递推公式:

f(x)=a*f(x-2)+b*f(x-1)+c

并给你f(1),f(2)的值,请求出f(n)的值,由于f(n)的值可能过大,求出f(n)对1000007取模后的值。

注意:-1对3取模后等于2

输入
第一行是一个整数T,表示测试数据的组数(T<=10000)
随后每行有六个整数,分别表示f(1),f(2),a,b,c,n的值。
其中0<=f(1),f(2)<100,-100<=a,b,c<=100,1<=n<=100000000 (10^9)
输出
输出f(n)对1000007取模后的值
样例输入
21 1 1 1 0 51 1 -1 -10 -100 3
样例输出
5999896
这题很明显就是矩阵快速幂,在构造初始矩阵时需要稍微思考下;

另外还得注意题目中说明了取模的规则 ,如:-1%3 = 2 ,所以在取模是一定要加上mod之后再取模!

 #include <iostream>#include <cstdlib>#include <cstdio>#include <cstring>#include <string>#include <algorithm>#include <set>#include <queue>using namespace std;const int mod = 1000007;const int MAXN = 1000000;long long f[MAXN + 10];int a,b,c,n;typedef struct Node{    long long a[3][3];} node;node fun(node a,node b){    node x = {0,0,0,              0,0,0,              0,0,0             };    for(int i = 0; i < 3; i++)    {        for(int j = 0; j < 3; j++)        {            for(int k = 0; k < 3; k++)                x.a[i][j] += a.a[i][k] * b.a[k][j],                             x.a[i][j] = (x.a[i][j] + mod) % mod;        }    }    return x;}long long quickpow(long long n){    node ans = {1,0,0,                0,1,0,                0,0,1               };    node tem = {b,1,0,                a,0,0,                c,0,1               };    while(n)    {        if(n & 1)ans = fun(ans,tem);        n >>= 1;        tem = fun(tem,tem);    }    return ((f[2] * ans.a[0][0] + mod) % mod + (f[1] * ans.a[1][0] + mod) % mod + ans.a[2][0]) % mod;}int main(){//    freopen("in.txt","r",stdin);    int t;    scanf("%d",&t);    while(t --)    {        scanf("%lld%lld%d%d%d%d",&f[1],&f[2],&a,&b,&c,&n);        if(n <= 2)printf("%lld\n",f[n]);        else      printf("%lld\n",quickpow(n - 2));    }    return 0;}        


1 0
原创粉丝点击