HDU - problem 1757 A Simple Math Problem【矩陣 + 快速冪】

A Simple Math Problem

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4283    Accepted Submission(s): 2573


Problem Description
Lele now is thinking about a simple function f(x).

If x < 10 f(x) = x.
If x >= 10 f(x) = a0 * f(x-1) + a1 * f(x-2) + a2 * f(x-3) + …… + a9 * f(x-10);
And ai(0<=i<=9) can only be 0 or 1 .

Now, I will give a0 ~ a9 and two positive integers k and m ,and could you help Lele to caculate f(k)%m.
 

Input
The problem contains mutiple test cases.Please process to the end of file.
In each case, there will be two lines.
In the first line , there are two positive integers k and m. ( k<2*10^9 , m < 10^5 )
In the second line , there are ten integers represent a0 ~ a9.
 

Output
For each case, output f(k) % m in one line.
 

Sample Input
10 9999 1 1 1 1 1 1 1 1 1 1 20 500 1 0 1 0 1 0 1 0 1 0
 

Sample Output
45 104
 

Author
linle
 

Source
 

Recommend
lcy   |   We have carefully selected several similar problems for you:  1575 1588 3117 2276 2256 

這道題算是矩陣算法的一個模板題了,構造矩陣,運用快速冪求解。

#include <map>
#include <set>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <iostream>
#include <stack>
#include <cmath>
#include <string>
#include <vector>
#include <cstdlib>
//#include <bits/stdc++.h>
//#define LOACL
#define space " "
using namespace std;
typedef long long LL;
typedef __int64 Int;
typedef pair<int, int> paii;
const int INF = 0x3f3f3f3f;
const double ESP = 1e-5;
const double PI = acos(-1.0);
const int MOD = 1e9 + 7;
const int MAXN = 100 + 10;
int n, mod, m;
struct Matrix {
	LL m[MAXN][MAXN];
	int row, col;
};
Matrix ori, res, u;
void init() {
	n = 10;
	memset(res.m, 0, sizeof(res.m));
	ori.row = ori.col = n;
}
void scan_in() {
	for (int i = 1; i <= n; i++) {
		scanf("%d", &ori.m[1][i]);
	}
    for(int i = 1; i <= n; i++) {
		ori.m[i][i-1] =1 ;
    }
	u.row = n; u.col = 1;
	for (int i = 1; i <= n; i++) {
		u.m[n - i + 1][1] = i - 1;
	}
}
Matrix multi(Matrix x, Matrix y) {
	Matrix z;
	memset(z.m, 0, sizeof(z.m));
	z.row = x.row; z.col = y.col;
	for (int i = 1; i <= x.row; i++) {
		for (int k = 1; k <= x.col; k++) {
			for (int j = 1; j <= y.col; j++) {
				z.m[i][j] += x.m[i][k]*y.m[k][j]%mod;
			}
			z.m[i][k] %= mod;
		}
	}
	return z;
}
Matrix pow_mod(Matrix a, int x){
	Matrix b;
	b.col = a.col; b.row = a.row;
	memset(b.m, 0, sizeof(b.m));
	for (int i = 1; i <= n; i++) {
		b.m[i][i] = 1;
	}
    while(x){
        if(x&1) b = multi(a,b);
        a = multi(a, a);
        x >>= 1;
    }
    return b;
}
int main() {
	while (scanf("%d%d", &m, &mod) != EOF) {
		init(); scan_in(); int ans = 0;
		if (m < 10) {printf("%d\n", m%mod); continue;}
		res = pow_mod(ori, m - 9);
		for(int i = 1;i <= 10; i++) {
			ans += (res.m[1][i]*(10 - i))%mod;
		}
		printf("%d\n", ans%mod);
	}
	return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章