HDU 1757 A Simple Math 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


題意很簡單,公式給出來了,不過找循環節的話不太靠譜,應該可以,可是沒去細想。這道題的公式是類似斐波那契數列的,所以用矩陣快速冪妥妥可以解出來。

本題用矩陣求解公式如下:


這個公式是由以下公式推導而來的:


只要先求出後面的方陣的冪,然後再求fn即可。

只要是類似斐波那契的數列都可以用上面的公式變形求得。

至於矩陣可以寫一個結構體或者類,然後重載一下*和%就可以直接套用快速冪的模板了,本題的快速冪是位運算模式的,所以就直接重載掉^了


代碼:

#include<iostream>
using namespace std;

int M;

class mat
{

	
public:
int num[10][10];
	void sete()
	{
		for (int i = 0; i<10; i++)
		for (int j = 0; j<10; j++)
		{
			if (i == j) num[i][j] = 1;
			else num[i][j] = 0;
		}
	}
	void setone(int *a)
	{
		for (int i = 0; i<10; i++)
			num[0][i] = a[i];
		for (int i = 1; i<10; i++)
		for (int j = 0; j<10; j++)
		{
			if (i - 1 == j) num[i][j] = 1;
			else num[i][j] = 0;
		}
	}
	mat operator * (const mat& ano)
	{
		mat ans;
		for (int i = 0; i<10; i++)
		{
			for (int j = 0; j<10; j++)
			{
				ans.num[i][j]=0;
				for (int k = 0; k<10; k++)
				ans.num[i][j] += (((this->num)[i][k])*((ano.num)[k][j])%M);
				
				ans.num[i][j]=ans.num[i][j]%M;
			}	
		}		
		return ans;
	}
	mat operator %(int m)
	{
		mat ans;
		for (int i = 0; i<10; i++)
		for (int j = 0; j<10; j++)
			ans.num[i][j] = this->num[i][j] % m;
		return ans;
	}
	mat operator ^(int b) 
	{
		mat a = *this;
		mat res;
		res.sete();
		while (b) {
			if (b & 1)
				res = res * a;
			a = a * a;
			b >>= 1;
		}
		return res;
	}
};

int basenum[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

int main()
{
	int a[10];
	int k;
	while (cin >> k >> M)
	{
		for (int i = 0; i<10; i++)
			cin >> a[i];
		if (k<10)
		{
			cout << basenum[k] % M << endl;
			continue;
		}
		mat one;
		one.setone(a);
		mat two;
		two = one^(k-9);
		int ans = 0;
		for (int i = 0; i < 10; i++)
			ans = (ans + two.num[0][i]*(9-i)) % M;
		cout << ans % M << endl;
	}
	return 0;
}


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