HDU4565(SummerTrainingDay05-C 矩阵快速幂)

So Easy!

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

Problem Description

  A sequence Sn is defined as:
HDU4565(SummerTrainingDay05-C 矩阵快速幂)
Where a, b, n, m are positive integers.┌x┐is the ceil of x. For example, ┌3.14┐=4. You are to calculate Sn.
  You, a top coder, say: So easy! 
HDU4565(SummerTrainingDay05-C 矩阵快速幂)
 

Input

  There are several test cases, each test case in one line contains four positive integers: a, b, n, m. Where 0< a, m < 215, (a-1)2< b < a2, 0 < b, n < 231.The input will finish with the end of file.
 

Output

  For each the case, output an integer Sn.
 

Sample Input

2 3 1 2013
2 3 2 2013
2 2 1 2013
 

Sample Output

4
14
4
 
根据条件可证(a-√b)n小于1,(a+√b)n向上取整即为求(a+√b)n + (a-√b)n,问题又转换为a^n+b^n的形式。
 //2017-08-05
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define ll long long using namespace std; ll a, b, n;
ll p, q;
const int N = ;
ll MOD; struct Matrix
{
ll a[N][N];
int r, c;
}ori, res; void init()
{
memset(res.a, , sizeof(res.a));
res.r = ; res.c = ;
res.a[][] = p;
res.a[][] = ;
ori.r = ; ori.c = ;
ori.a[][] = p;
ori.a[][] = ;
ori.a[][] = -q;
ori.a[][] = ;
} Matrix multi(Matrix x, Matrix y)
{
Matrix z;
memset(z.a, , sizeof(z.a));
z.r = x.r, z.c = y.c;
for(int i = ; i <= x.r; i++)
{
for(int k = ; k <= x.c; k++)
{
if(x.a[i][k] == ) continue;
for(int j = ; j<= y.c; j++)
z.a[i][j] = (z.a[i][j] + (x.a[i][k] * y.a[k][j]) % MOD + MOD) % MOD;
}
}
return z;
} void Matrix_pow(int n)
{
while(n)
{
if(n & )
res = multi(res, ori);
ori = multi(ori, ori);
n >>= ;
}
printf("%lld\n", res.a[][] % MOD);
} int main()
{
while(scanf("%lld%lld%lld%lld", &a, &b, &n, &MOD)!=EOF){
p = *a;
q = a*a-b;
init();
if(n == )printf("2\n");
else if(n == )printf("%lld\n", p);
else Matrix_pow(n-);
} return ;
}
Source
上一篇:使用vim时生成的.swp文件


下一篇:Nginx 之并发优化