uva 10655 - Contemplation! Algebra 【矩阵快速幂】【最坑的输入】
2015-12-14 20:33
411 查看
题意:令a*b = q, a+b = p,现在给你q、 p、 n,问你a^n + b^n的值。
构造矩阵吧,比较简单。
但输入太坑爹了,上面说的是——Input is terminatedby a line containing only two zeroes.当输入一行只有两个0时结束,用while(scanf("%d%d", &p, &q), p || q)就悲剧了。
思路:((a-1)^n + (b-1)^n) * (a + b) = a^n + b^n + ((a-2)^n+(b-2)^n) * a*b。
令f(n) = a^n + b^n,则有公式f(n) + f(n-2)*q = f(n-1)*p。
构造矩阵就可以KO了。
AC代码:
构造矩阵吧,比较简单。
但输入太坑爹了,上面说的是——Input is terminatedby a line containing only two zeroes.当输入一行只有两个0时结束,用while(scanf("%d%d", &p, &q), p || q)就悲剧了。
思路:((a-1)^n + (b-1)^n) * (a + b) = a^n + b^n + ((a-2)^n+(b-2)^n) * a*b。
令f(n) = a^n + b^n,则有公式f(n) + f(n-2)*q = f(n-1)*p。
构造矩阵就可以KO了。
AC代码:
#include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <algorithm> #include <queue> #include <stack> #include <map> #include <set> #include <vector> #define INF 0x3f3f3f #define eps 1e-8 #define MAXN (2000+1) #define MAXM (100000) #define Ri(a) scanf("%d", &a) #define Rl(a) scanf("%lld", &a) #define Rf(a) scanf("%lf", &a) #define Rs(a) scanf("%s", a) #define Pi(a) printf("%d\n", (a)) #define Pf(a) printf("%.2lf\n", (a)) #define Pl(a) printf("%lld\n", (a)) #define Ps(a) printf("%s\n", (a)) #define W(a) while(a--) #define CLR(a, b) memset(a, (b), sizeof(a)) #define MOD 1000000007 #define LL long long #define lson o<<1, l, mid #define rson o<<1|1, mid+1, r #define ll o<<1 #define rr o<<1|1 using namespace std; struct Matrix { LL a[3][3]; int r, c; }; Matrix ori, res; Matrix multi(Matrix x, Matrix y) { Matrix z; z.r = x.r; z.c = y.c; CLR(z.a, 0); for(int i = 0; i < x.r; i++) { for(int k = 0; k < x.c; k++) { if(x.a[i][k] == 0) continue; for(int j = 0; j < y.c; j++) z.a[i][j] += x.a[i][k] * y.a[k][j]; } } return z; } void init_M(LL p, LL q) { ori.r = ori.c = res.r = res.c = 2; CLR(ori.a, 0); CLR(res.a, 0); res.a[0][0] = res.a[1][1] = 1; ori.a[0][0] = p; ori.a[0][1] = 1; ori.a[1][0] = -q; } LL F[3]; void solve(LL n) { while(n > 0) { if(n & 1) res = multi(ori, res); ori = multi(ori, ori); n >>= 1; } LL ans = F[0] * res.a[0][0] + F[1] * res.a[1][0]; Pl(ans); } int main() { LL p, q, n; while(scanf("%lld%lld%lld", &p, &q, &n) == 3) { F[0] = p; F[1] = 2; if(n <= 1) { Pl(F[1-n]); continue; } init_M(p, q); solve(n-1); } return 0; }
相关文章推荐
- myeclipse快捷键
- hdoj 5597 GTW likes function 【打表找规律】
- ARM926 interrupts in QEMU
- 一个数字与时间切换的函数
- spring中的5中自动装配方案
- 109 Convert Sorted List to Binary Search Tree
- ajax实现提交数据并且不跳转
- OpenStack-RPC-server的构建(一)
- android中JSON的解析
- SecureCRT中文显示乱码的解决方法
- hdoj 5596 GTW likes gt 【思维】
- 服务器共享文件夹设置软件、局域网共享文件夹加密工具、文件共享服务器软件的选择
- hdoj 5595 GTW likes math 【水题】
- 权限框架的搭建
- uva 10635-Prince and Princess 【LIS 求解 LCS】
- VS2013 无法打开包括文件:“cv.h”
- LA 3882 - And Then There Was One 【约瑟夫环变形】
- 自己动手写cocos2dx游戏引擎(一)——引擎入口
- RESTful
- 行为型模式(二)