nefu A Simple Math Problem 459 (矩阵连乘)

A Simple Math Problem

Problem : 459

Time Limit : 1000ms

Memory Limit : 65536K

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

hint

 

source

题意:

已知函数f(x)满足条件:

(1) 当x<10时,f(x)=x;

(2) 当x>=10时,f(x)=a0*f(x-1)+a1*f(x-2)+......+an*f(x-10).

其中a0--an是输入的数字,且只能为0或1,给定n和m,求f(n)%m的值。

思路:

可以构造矩阵为

 f[n]  a0  a1  a2  ...  a9  f[n-1]
 f[n-1]  1   0   0   ...  0  f[n-2]
 f[n-2]   0   1   0   ...  0   f[n-3]
    .    = . . .   . *      .
    .  .  . .   .     .
    .  . . .   .     .
 f[n-9]   0 0 0   ...  0  f[n-10]
有了递推式即可用矩阵快速幂解决。。

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#define ll long long
#define N 10
using namespace std;
ll n,m;
struct mat
{
	ll m[N][N];
};
mat I;
void init()
{
	int i,j;
	for(i=0;i<N;i++)
		for(j=0;j<N;j++)
			I.m[i][j]=(i==j);
}
mat multi(mat a,mat b)
{
	int i,j,k;
	mat c;
	for(i=0;i<N;i++)
	{
		for(j=0;j<N;j++)
		{
			c.m[i][j]=0;
			for(k=0;k<N;k++)
			{
				c.m[i][j]+=a.m[i][k]*b.m[k][j]%m;
			}
			c.m[i][j]%=m;
		}
	}
	return c;
}
mat power(mat a,ll k)
{
	mat ans=I,p=a;
	while(k)
	{
		if(k&1)
		{
			ans=multi(ans,p);
			k--;
		}
		k>>=1;
		p=multi(p,p);
	}
	return ans;
}
int main()
{
	init();
	mat a;
	int i,j;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		for(i=0;i<N;i++)
		{
			for(j=0;j<N;j++)
			{
				a.m[i][j]=0;
			}
		}
		for(i=0;i<10;i++)
		{
			ll x;
			scanf("%lld",&x);
			a.m[0][i]=x;
		}
		int i=1,j=0;
		while(j<9)
		{
			a.m[i][j]=1;
			i++;j++;
		}
		if(n<10)
			printf("%lld\n",n%m);
		else
		{
			n-=9;
			mat ans=power(a,n);
			ll cnt=0;
			for(i=0;i<10;i++)
				cnt=(cnt+(9-i)*ans.m[0][i])%m;
			printf("%lld\n",cnt);
		}
	}
	return 0;
} 


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值