UVA 10870 Recurrences

Recurrences

Consider recurrent functions of the following form:

f(n) = a1 f(n - 1) + a2 f(n - 2) + a3 f(n - 3) + ... + ad f(n - d), for n > d.
a1, a2, ..., ad - arbitrary constants.

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 = 1, a2 = 1.

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: dnm, followed by two sets of d non-negative integers. The first set contains coefficients: a1, a2, ..., ad. The second set gives values of f(1), f(2), ..., f(d).

You can assume that: 1 <= d <= 15, 1 <= n <= 231 - 1, 1 <= m <= 46340. All numbers in the input will fit in signed 32-bit integer.

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 m) on a separate line. It must be a non-negative integer, less than m.


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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值