杭電oj1757:A Simple Math Problem(矩陣快速冪)

A Simple Math Problem

題目鏈接

Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

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

矩陣快速冪詳解:鏈接

矩陣快速冪方法(模板):

#include<iostream>
#include<cstring>
using namespace std;

typedef long long LL;
const int maxn = 15;

struct Matrix{
	LL matrix[maxn][maxn];
}ori, ans;//ori矩陣存放冪運算結果,ans存放結果 

int n=10, k, m;

void init()//初始化工作 
{
	for(int i=0;i<n;i++)
		for(int j=0;j<n;j++)
			ori.matrix[i][j] = ans.matrix[i][j] = 0;
	for(int i=0;i<n;i++)
	{
		cin>>ori.matrix[0][i];
		ori.matrix[i+1][i] = 1;
		ans.matrix[i][0] = 9-i;
	}
}

//矩陣相乘 
Matrix multiply(Matrix a, Matrix b)
{
	Matrix temp;
	memset(temp.matrix, 0, sizeof(temp.matrix));
	for(int i=0;i<n;i++)
		for(int j=0;j<n;j++)
			for(int k=0;k<n;k++)
				temp.matrix[i][j] = (temp.matrix[i][j] % m + (a.matrix[i][k] % m * b.matrix[k][j] % m) % m) % m;
	return temp;
}

//矩陣的b次冪 
Matrix binaryPow(int b)
{
	Matrix temp;
	memset(temp.matrix, 0, sizeof(temp.matrix));
	for(int i=0;i<n;i++)
		temp.matrix[i][i] = 1;
	while(b > 0)
	{
		if(b & 1)
			temp = multiply(temp, ori);
		ori = multiply(ori, ori);
		b >>= 1;
	}
	return temp;
}

int main()
{
	//freopen("in.txt", "r", stdin);
	while(cin>>k>>m)
	{
		if(k < n)
		{
			cout<<k<<endl;
			continue;
		}
		init();
		Matrix temp = binaryPow(k-9);//矩陣的k-9次冪 
		ans = multiply(temp, ans);
		cout<<ans.matrix[0][0]<<endl;
	}
	return 0;
}
發佈了30 篇原創文章 · 獲贊 14 · 訪問量 1830
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章