Uva10655 Contemplation! Algebra矩阵快速幂
来源:互联网 发布:mac死机自动重启 编辑:程序博客网 时间:2024/06/06 00:44
题目描述:
已知a + b = p , ab = q , 求a^n + b^n的值,a和b有可能是虚数;
思路:设S(n) = a^n + b^n,则S(n) = a ^ n + b ^ n = (a + b)^(a^(n - 1) + b^(n - 1)) - a* b^(n - 1) - a ^(n - 1) * b = p * S(n - 1) - ab * (a^(n - 2) + b ^(n - 2)) = p * S(n - 1) - q * S(n - 2)
由此可见,构造矩阵使用快速幂来求解即可
#include <bits/stdc++.h>#define LL long long#define mem(a , x) memset(a , x , sizeof(a))using namespace std;int n;struct Matrix{ LL a[3][3]; Matrix(int x = 0){ mem(a , 0); for(int i = 1 ; i <= n; i++){ a[i][i] = x; } } Matrix operator+(const Matrix& B){ Matrix res; for(int i = 1 ; i <= n; i++){ for(int j = 1 ;j <= n ; j++){ res.a[i][j] = a[i][j] + B.a[i][j]; } } return res; } Matrix operator*(const Matrix& B){ Matrix res; for(int i = 1 ;i <= n ; i++){ for(int j = 1 ; j<= n;j ++){ for(int k = 1 ; k <= n; k++){ res.a[i][j] += a[i][k] * B.a[k][j]; } } } return res; } Matrix operator^ (int t){ Matrix A = (*this) , res(1); while(t){ if(t & 1) res = res * A; A = A * A; t >>= 1; } return res; }};int main(){ n = 2; int N; LL p , q; Matrix base , mul; while(scanf("%lld %lld" , &p , &q) != EOF){ if(scanf("%d" , &N) != 1) break; if(N == 0) puts("2"); else if(N == 1) printf("%d\n" , p); else if(N == 2) printf("%lld\n" , p * p - 2LL * q); if(N <= 2) continue; base.a[1][1] = p * p - 2LL * q; base.a[1][2] = p; base.a[2][1] = p; base.a[2][2] = 2LL; mul.a[1][1] = p; mul.a[1][2] = 1LL; mul.a[2][1] = -q; mul.a[2][2] = 0; int t = N - 2; Matrix Q = mul^t; Matrix ans = base * Q; LL res = ans.a[1][1]; printf("%lld\n" , res); } return 0;}
阅读全文
0 0
- Contemplation! Algebra(矩阵快速幂,uva10655)
- Uva10655 Contemplation! Algebra矩阵快速幂
- UVA10655-Contemplation! Algebra
- uva 10655 Contemplation! Algebra 矩阵快速幂
- UVA 10655 - Contemplation! Algebra(矩阵快速幂)
- uva 10655 - Contemplation! Algebra(矩阵快速幂)
- UVA-10655 Contemplation! Algebra (矩阵快速幂)
- UVA 10655 Contemplation! Algebra(矩阵快速幂)
- UVA 10655 Contemplation! Algebra (矩阵快速幂)
- UVA 10655 Contemplation! Algebra(构造矩阵和快速幂)
- uva 10655 Contemplation! Algebra(矩阵快速幂)
- uva 10655 Contemplation! Algebra(矩阵快速幂)
- 【矩阵快速幂+输入终止条件判断】Contemplation! Algebra UVA
- 矩阵快速幂uva10655
- uva10655(矩阵快速幂)
- uva 10655 - Contemplation! Algebra 【矩阵快速幂】【最坑的输入】
- UVA10655矩阵快速幂(构造矩阵)
- UVA 10655 Contemplation! Algebra(矩阵乘法)
- windows下配置OpenGL环境(glut、freeglut、glew等工具)
- TCP/IP协议栈的基本工作原理
- 获取JAVA当前进程PID的两种方法
- 算法概论第八章练习题 8.3
- javascript深拷贝和浅拷贝
- Uva10655 Contemplation! Algebra矩阵快速幂
- AOE网上的关键路径——spfa+前向星
- 我要通过!
- k-近邻算法
- zoj 1610 Count the Colors(线段树)(成段更新染色)
- 面试题:合并两个有序链表
- jozj. 3511. 【NOIP2013模拟11.5A组】cza的蛋糕(cake)
- c++primer plus第四版答案第十章
- 微软100题--004