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取模后的值 样例输入
-
2 1 1 1 1 0 5 1 1 -1 -10 -100 3
样例输出
-
5 999896
-
第一行是一个整数T,表示测试数据的组数(T<=10000)
另外还得注意题目中说明了取模的规则 ,如:-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;
}