NYOJ 301 递推求值【矩阵快速幂】
来源:互联网 发布:腐烂国度生命线优化 编辑:程序博客网 时间:2024/04/29 19:18
题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=301
题目分析:
给你一个递推公式:f(x)=a*f(x-2)+b*f(x-1)+c
并给你f(1),f(2),a,b,c,n的值,请求出f(n)的值,由于f(n)的值可能过大,求出f(n)对1000007取模后的值。
由于题目的数据范围较大,直接按递推式暴力求解肯定不行。重点是构造矩阵,用矩阵乘法来写。本题要构造两个矩阵,一个是初始矩阵:
f2 0 0
f1 0 0
1 0 0
另一个矩阵B为:
b a c
1 0 0
0 0 1
因为F(2)和F(1)是已知的,当n>=3时,每次都乘以矩阵B,就能推出下一个矩阵。而矩阵的第一行第一列的元素就是所求的结果。所以当N很大时,用矩阵快速幂来求解。
矩阵相乘时要注意乘的顺序,顺序不同结果也就不同。刚开始把矩阵乘反了,总是对不上样例,后来才发现。
AC代码:
#include<stdio.h>#include<algorithm>#include<iostream>#include<string.h>typedef long long LL;#define mod 1000007using namespace std;struct node{ LL mat[3][3]; node() { memset(mat,0,sizeof(mat)); for(int i=0; i<3; i++) mat[i][i]=1;//单位矩阵 }};node multi(node x,node y)//两矩阵相乘{ node res; for(int i=0; i<3; i++) { for(int j=0; j<3; j++) { res.mat[i][j]=0; for(int k=0; k<3; k++) { res.mat[i][j]+=x.mat[i][k]*y.mat[k][j]; res.mat[i][j]=(res.mat[i][j]+mod)%mod; } } } return res;}node Pow(node x,int m)//矩阵快速幂{ node res; while(m) { if(m&1) { res=multi(res,x); for(int i=0; i<3; i++) { for(int j=0; j<3; j++) res.mat[i][j]=(res.mat[i][j]+mod)%mod; } } x=multi(x,x); for(int i=0; i<3; i++) { for(int j=0; j<3; j++) x.mat[i][j]=(x.mat[i][j]+mod)%mod; } m>>=1; } return res;}int main(){ int t; scanf("%d",&t); while(t--) { LL f1,f2,a,b,c,n; scanf("%lld%lld%lld%lld%lld%lld",&f1,&f2,&a,&b,&c,&n); if(n==0) { printf("%lld\n",(f2-f1*b-c+mod)%mod); continue; } if(n==1) { printf("%lld\n",(f1+mod)%mod); continue; } if(n==2) { printf("%lld\n",(f2+mod)%mod); continue; } node ans1,ans2,ans; memset(ans1.mat,0,sizeof(ans1.mat)); memset(ans2.mat,0,sizeof(ans2.mat)); memset(ans.mat,0,sizeof(ans.mat)); ans1.mat[0][0]=f2,ans1.mat[1][0]=f1,ans1.mat[2][0]=1; ans2.mat[0][0]=b,ans2.mat[0][1]=a,ans2.mat[0][2]=c; ans2.mat[1][0]=ans2.mat[2][2]=1; ans=multi(Pow(ans2,n-2),ans1);// for(int i=0; i<3; i++)// {// for(int j=0; j<3; j++)// printf("%lld ",(ans.mat[i][j]+mod)%mod);// printf("\n");// } printf("%lld\n",(ans.mat[0][0]+mod)%mod); } return 0;}
0 0
- NYOJ - 301 - 递推求值 ( 递推+矩阵快速幂 )
- NYOJ 301 递推求值(矩阵快速幂)
- nyoj 301递推求值 (矩阵+快速幂)
- nyoj--301 递推求值(矩阵快速幂)
- NYOJ 301 递推求值【矩阵快速幂】
- nyoj 301 递推求值 矩阵快速幂
- NYOJ 301 递推求值【矩阵快速幂】
- nyoj 301 递推求值(矩阵快速幂)
- 【矩阵快速幂*模板】nyoj 301 递推求值
- nyoj 301递推求值(矩阵快速幂的递推求值)
- nyoj 301 递推求值 矩阵幂
- NYOJ 301 递推求值【矩阵快速幂取模】
- 矩阵快速幂 - hduoj 5667 Sequence -nyoj 301 递推求值
- NYOJ——301递推求值(矩阵快速幂)
- nyoj 301 递推求值【常数矩阵】
- NYOJ-301 递推求值【矩阵二分幂】
- nyoj 301 递推求值(矩阵递推)
- nyoj301递推求值【矩阵快速幂】
- 一个acm过来人的心得
- 小数取舍
- android 各种系统设置的操作
- Merge Two Sorted Lists
- 日期转换JSTL JSP 页面显示日期格式设置
- NYOJ 301 递推求值【矩阵快速幂】
- 数学符号arg含义
- ThinkPHP3.0主入口配置,注册、登录案例
- YUV420转YUV444
- #JS#构造子(constructor)
- osi系统模型和tcp/ip模型
- 初探OpenCV+GPU
- http详解
- C++之赋值函数和析构函数