UVA 10870 Recurrences
来源:互联网 发布:java round half up 编辑:程序博客网 时间:2024/05/01 15:58
Recurrences
Consider recurrent functions of the following form:
f(n) = a1
a1, a2, ..., ad
A famous example is the Fibonacci sequence, defined as: f(1) = 1, f(2) = 1, f(n) = f(n - 1) + f(n - 2). Here d = 2, a1
Every such function is completely described by specifying d (which is called the order of recurrence), values of d coefficients: a1, a2, ..., ad, and values of f(1), f(2), ..., f(d). You'll be given these numbers, and two integers n and m. Your program's job is to compute f(n) modulo m.
Input
Input file contains several test cases. Each test case begins with three integers:
You can assume that: 1 <=
Input is terminated by line containing three zeroes instead of d, n, m. Two consecutive test cases are separated by a blank line.
Output
For each test case, print the value of f(n) (mod
Sample Input
1 1 100
2
1
2 10 100
1 1
1 1
3 2147483647 12345
12345678 0 12345
1 2 3
0 0 0
Output for Sample Input
1
55
423
#include <cstdio>#include <cstring>typedef long long LL;const int N = 16;LL MOD;struct Matrix{LL ary[N][N];void init() {memset(ary, 0, sizeof(ary));}Matrix() {init();}};const Matrix operator*(const Matrix & A, const Matrix & B) {Matrix t;for (int i = 0; i < N; ++i)for (int j = 0; j < N; ++j) {for (int k = 0; k < N; ++k) t.ary[i][j] += A.ary[i][k] * B.ary[k][j];t.ary[i][j] %= MOD;}return t;}LL quick_pow(int d, LL n) {Matrix ans, tmp;for (int i = 0; i < d; ++i) {scanf("%lld", &tmp.ary[i][0]);tmp.ary[i][i + 1] = 1;}for (int i = 0; i < d; ++i) scanf("%lld", &ans.ary[0][d - i - 1]);if (n <= d)return ans.ary[0][n - 1];n -= d;while (n) {if (n & 1)ans = ans * tmp;n >>= 1;tmp = tmp * tmp;}return ans.ary[0][0];}int main() {int d;LL n, m;while (~scanf("%d%lld%lld", &d, &n, &m), (d || n || m)) {MOD = m;LL ans = quick_pow(d, n);printf("%lld\n", ans);}return 0;}
- uva 10870 Recurrences
- uva 10870 Recurrences
- UVA 10870 Recurrences
- UVA 10870(p155)----Recurrences
- UVA 10870 Recurrences
- uva 10870 Recurrences
- UVA 10870 Recurrences 矩阵乘法
- UVA 10870 Recurrences 矩阵乘法
- UVA - 10870 Recurrences(构造矩阵)
- 7.22 F uva 10870 Recurrences
- Recurrences UVA
- Recurrences UVA
- UVA 10870 Recurrences 矩阵快速幂
- uva 10870 - Recurrences(矩阵乘法)
- UVa 10870 Recurrences / 矩阵快速幂
- uva 10870 Recurrences(矩阵优化递推)
- UVA 10870 - Recurrences(矩阵快速幂)
- uva 10870 - Recurrences(矩阵快速幂)
- hdu4418 Time travel(高斯消元法+概率)
- HDU_3376_Matrix Again(最小费用流)
- jqMobi指南系列教程是《 jqMobi Javascript Frameworks Cheat Sheet》 的中文版现在改名为app framework
- segmentedControl与swipe联合控制页面
- QT中QTimer的使用方法介绍
- UVA 10870 Recurrences
- atexit http://www.cnblogs.com/wanghetao/archive/2012/04/03/2431256.html
- Linux下的常用shell命令
- hadoop 自学指南八之Hive(2)
- 并发和并行
- 1280:前m大的数
- python3 入门 (一) 基础语法
- jqmobi(appframework) 小技巧记录
- 深入理解Android—WebView