Funny Function(HDU 6050)

来源:互联网 发布:软件风险分析 编辑:程序博客网 时间:2024/05/21 10:43

Funny Function

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1045    Accepted Submission(s): 498


Problem Description
Function Fx,ysatisfies:

For given integers N and M,calculate Fm,1 modulo 1e9+7.
 

Input
There is one integer T in the first line.
The next T lines,each line includes two integers N and M .
1<=T<=10000,1<=N,M<2^63.
 

Output
For each given N and M,print the answer in a single line.
 

Sample Input
22 23 3
 

Sample Output
233


 //题意:不解释

//思路:比赛的时候一直和队友在求通项,失败了...看了题解发现可以用矩阵解,题解已经解释的很详细了,直接上题解吧。

题解对于任意i>=1,当j>=3时,有 1 

通过归纳法可以得到 2 (两项两项合并可以消掉中间项)


进而推导出 3 

通过矩阵快速幂求解

A矩阵是[0 2]       B0是[1 0]        B1是[-1 2]
                1 1                   0 1                    1 0

推出来可以验证下。


#include <iostream>#include <cstdio>#include <cstring>#include <string>#include <cmath>#include <algorithm>using namespace std;const int mod = 1e9 + 7;typedef struct {long long m[3][3];}Matrix;long long  n, m;Matrix Mul(Matrix a, Matrix b){Matrix c;memset(c.m, 0, sizeof(c.m));for (int i = 0; i < 2; i++){for (int j = 0; j < 2; j++){for (int k = 0; k < 2; k++){c.m[i][j] += ((a.m[i][k] * b.m[k][j]) % mod + mod) % mod;}}}return c;}Matrix fastm(Matrix a, long long num){Matrix res;memset(res.m, 0, sizeof(res.m));res.m[0][0] = res.m[1][1] = 1;while (num){if (num & 1)res = Mul(res, a);num >>= 1;a = Mul(a, a);}return res;}int main(){int T;scanf("%d", &T);while (T--){scanf("%lld%lld", &n, &m);Matrix a;a.m[0][0] = 0;a.m[0][1] = 2;a.m[1][0] = 1;a.m[1][1] = 1;a = fastm(a, n);if (n % 2 == 0){a.m[0][0] = ((a.m[0][0] - 1) + mod) % mod;a.m[1][1] = ((a.m[1][1] - 1) + mod) % mod;}else{a.m[0][0] = ((a.m[0][0] + 1) % mod + mod) % mod;a.m[0][1] = ((a.m[0][1] - 2) + mod) % mod;a.m[1][0] = ((a.m[1][0] - 1) + mod) % mod;}a = fastm(a, m - 1);long long ans = (a.m[0][0] + a.m[1][0]) % mod;printf("%lld\n", ans);}return 0;}



原创粉丝点击