博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HDU 1005 Number Sequence
阅读量:4657 次
发布时间:2019-06-09

本文共 2174 字,大约阅读时间需要 7 分钟。

Problem Description

A number sequence is defined as follows:
f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
Given A, B, and n, you are to calculate the value of f(n).

Input

The input consists of multiple test cases. Each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000). Three zeros signal the end of input and this test case is not to be processed.

Output

For each test case, print the value of f(n) on a single line.

Sample Input

1 1 3 1 2 10 0 0 0

Sample Output

2 5
 
题解:矩阵乘优化斐波那契的变形题,原本的公式是
        
   它实际上是
        
   每次进行一次
        
   这样的变换。
   在这道题中我们将变换稍微改变一下,变成每次
        
   
CODE:
#include 
#include
#include
#define REP(i, s, n) for(int i = s; i <= n; i ++)#define REP_(i, s, n) for(int i = n; i >= s; i --)#define MAX_N 3#define mod 7using namespace std;int a, b, n;struct node{ int Mtx[MAX_N][MAX_N];}tmp, coe;node operator+(node a,node b){ node c; REP(i, 1, 2) REP(j, 1, 2){ c.Mtx[i][j] = (a.Mtx[i][j] + b.Mtx[i][j]) % mod; } return c;}node operator*(node a,node b){ node c; REP(i, 1, 2) REP(j, 1, 2){ c.Mtx[i][j] = 0; REP(k, 1, 2) c.Mtx[i][j] = (c.Mtx[i][j] + a.Mtx[i][k] * b.Mtx[k][j]) % mod; } return c;} node operator^(node a,int k){ if(k == 0){ memset(a.Mtx, 0, sizeof(a.Mtx)); REP(i, 1, 2) a.Mtx[i][i] = 1; return a; } if(k == 1) return a; node c = a ^ (k >> 1); if(k & 1) return c * c * a; return c * c;} int main(){ while(scanf("%d%d%d", &a, &b, &n) != EOF){ if(a == 0 && b == 0 && n == 0) break; if(n == 1) { cout << 1 << endl; continue; } if(n == 2) { cout << 1 << endl; continue; } else { tmp.Mtx[1][1] = a * 1 + b * 1; tmp.Mtx[1][2] = 1; tmp.Mtx[2][1] = 1; tmp.Mtx[2][2] = 1; coe.Mtx[1][1] = a; coe.Mtx[1][2] = 1; coe.Mtx[2][1] = b; coe.Mtx[2][2] = 0; n -= 3; coe = coe ^ n; tmp = tmp * coe; cout << tmp.Mtx[1][1] << endl; } } return 0;}

 

        

转载于:https://www.cnblogs.com/ALXPCUN/p/4588218.html

你可能感兴趣的文章
栈应用——逆波兰式表达式的值
查看>>
vscode 快速生成html
查看>>
div模拟textarea且高度自适应
查看>>
windows下vi/vim编辑器的基本操作
查看>>
负载均衡软件LVS分析二(安装)
查看>>
access INSERT INTO 语句的语法错误
查看>>
JQuery异步提交
查看>>
Python:将数组中的元素导出到变量中 (unpacking)
查看>>
ubuntu16.04安装mysql5.6
查看>>
mysql命令行中执行sql的几种方式总结
查看>>
ubantu 文件权限 Permission denied
查看>>
Python 多态 对象常用内置函数 运算符重载 对象迭代器 上下文管理
查看>>
Python 反射 元类 单例 冒泡
查看>>
Python socket 粘包问题 报头
查看>>
Python Django 数据库查询优化 事务
查看>>
Python django mtv与mvc ajax 分页器 序列化组件
查看>>
Python Django 多对多三种创建方式 form组件 cookie和session
查看>>
Python Django 生命周期 中间键 csrf跨站请求伪造 auth认证模块 settings功能插拔式源码...
查看>>
系统_Linux目录结构及功能
查看>>
安装_解决”此主机 Intel VT-x, 但Intel VT- x处于禁用状态“问题
查看>>