首页 技术 正文
技术 2022年11月15日
0 收藏 979 点赞 3,970 浏览 1138 个字

题目链接:https://vjudge.net/problem/UVA-10518

UVA10518 How Many Calls?  —— 矩阵快速幂

UVA10518 How Many Calls?  —— 矩阵快速幂

题解:

问:求斐波那契数f[n]的时候调用了多少次f[n] = f[n-1] + f[n-2],没有记忆化,一直递归到f[0]、f[1],其中f[0]、f[1]也算调用了一次。

设求f[n]调用了S[n]次,则可知: S[n] = S[n-1] + S[n-2] + 1。构造矩阵求解即可。

代码如下:

 #include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <string>
#include <set>
using namespace std;
typedef long long LL;
const int INF = 2e9;
const LL LNF = 9e18;
//const int MOD = 1e9+7;
const int MAXN = 1e6+; int MOD;
const int Size = ;
struct MA
{
LL mat[Size][Size];
void init()
{
for(int i = ; i<Size; i++)
for(int j = ; j<Size; j++)
mat[i][j] = (i==j);
}
}; MA mul(MA x, MA y)
{
MA ret;
memset(ret.mat, , sizeof(ret.mat));
for(int i = ; i<Size; i++)
for(int j = ; j<Size; j++)
for(int k = ; k<Size; k++)
ret.mat[i][j] += 1LL*x.mat[i][k]*y.mat[k][j]%MOD, ret.mat[i][j] %= MOD;;
return ret;
} MA qpow(MA x, LL y)
{
MA s;
s.init();
while(y)
{
if(y&) s = mul(s, x);
x = mul(x, x);
y >>= ;
}
return s;
} MA tmp ={
, , ,
, , ,
, ,
}; int main()
{
LL n, b, f[] = {,}, kase = ;
while(scanf("%lld%lld",&n,&b)&&(n||b))
{
MOD = b;
if(n<=)
{
printf("Case %lld: %lld %lld %lld\n", ++kase, n, b, f[n]%MOD);
continue;
} MA s = tmp;
s = qpow(s, n-);
LL ans = ((s.mat[][]+s.mat[][])%MOD+s.mat[][])%MOD;
printf("Case %lld: %lld %lld %lld\n", ++kase, n, b, ans);
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,104
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,580
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,428
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,835
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,918