1. 程式人生 > >Recurrences

Recurrences

連結

模板

struct Matrix
{
	ll n, m, a[30][30];
	ll* operator[](ll x){return a[x];}
	Matrix(ll x, ll y)
	{
		n=x, m=y;
		cl(a);
	}
	void show()
	{
		ll i, j;
		printf("Matrix %lld*%lld:\n",n,m);
		for(i=1;i<=n;i++)
		{
			for(j=1;j<=m;j++)printf("%lld ",a[i][j]);
			putchar(10);
		}
	}
};
Matrix operator*
(Matrix a, Matrix b) { Matrix t(a.n,b.m); ll i, j, k; for(i=1;i<=t.n;i++)for(j=1;j<=t.m;j++)for(k=1;k<=a.m;k++)t[i][j]=(t[i][j]+a[i][k]*b[k][j])%mod; return t; } Matrix operator+(Matrix a, Matrix b) { Matrix t(a.n,a.m); ll i, j; for(i=1;i<=t.n;i++)for(j=1;j<=t.m;j++)t[i][j]=(a[
i][j]+b[i][j])%mod; return t; } Matrix operator-(Matrix a, Matrix b) { Matrix t(a.n,a.m); ll i, j; for(i=1;i<=t.n;i++)for(j=1;j<=t.m;j++)t[i][j]=(a[i][j]-b[i][j]+mod)%mod; return t; } Matrix fastpow(Matrix a, ll b) { ll i, j; Matrix t(a.n,a.m), ans(a.n,a.m); for(i=1;i<=a.n;i++)for(j=
1;j<=a.m;j++)t[i][j]=a[i][j]; for(i=1;i<=a.n;i++)ans[i][i]=1; for(;b;b>>=1,t=t*t)if(b&1)ans=ans*t; return ans; }

宣告矩陣的時候必須要宣告行和列:Matrix m(a,b)

題解

矩陣快速冪模板題,一定要搞清楚行和列…我竟然調了一個多小時

程式碼

//矩陣
#include <bits/stdc++.h>
#define ll long long
#define cl(x) memset(x,0,sizeof(x))
using namespace std;
ll mod;
struct Matrix
{
	ll n, m, a[30][30];
	ll* operator[](ll x){return a[x];}
	Matrix(ll x, ll y)
	{
		n=x, m=y;
		cl(a);
	}
	void show()
	{
		ll i, j;
		printf("Matrix %lld*%lld:\n",n,m);
		for(i=1;i<=n;i++)
		{
			for(j=1;j<=m;j++)printf("%lld ",a[i][j]);
			putchar(10);
		}
	}
};
Matrix operator*(Matrix a, Matrix b)
{
	Matrix t(a.n,b.m);
	ll i, j, k;
	for(i=1;i<=t.n;i++)for(j=1;j<=t.m;j++)for(k=1;k<=a.m;k++)t[i][j]=(t[i][j]+a[i][k]*b[k][j])%mod;
	return t;
}
Matrix operator+(Matrix a, Matrix b)
{
	Matrix t(a.n,a.m);
	ll i, j;
	for(i=1;i<=t.n;i++)for(j=1;j<=t.m;j++)t[i][j]=(a[i][j]+b[i][j])%mod;
	return t;
}
Matrix operator-(Matrix a, Matrix b)
{
	Matrix t(a.n,a.m);
	ll i, j;
	for(i=1;i<=t.n;i++)for(j=1;j<=t.m;j++)t[i][j]=(a[i][j]-b[i][j]+mod)%mod;
	return t;
}
Matrix fastpow(Matrix a, ll b)
{
	ll i, j;
	Matrix t(a.n,a.m), ans(a.n,a.m);
	for(i=1;i<=a.n;i++)for(j=1;j<=a.m;j++)t[i][j]=a[i][j];
	for(i=1;i<=a.n;i++)ans[i][i]=1;
	for(;b;b>>=1,t=t*t)if(b&1)ans=ans*t;
	return ans;
}
int main()
{
	ll d, n, a[20], i;
	while(scanf("%lld%lld%lld",&d,&n,&mod),d)
	{
		Matrix f(d,1), trans(d,d);
		for(i=1;i<d;i++)trans[i][i+1]=1;
		for(i=1;i<=d;i++)scanf("%lld",&trans[d][d-i+1]);
		for(i=1;i<=d;i++)scanf("%lld",&f[i][1]);
		f=fastpow(trans,n-1)*f;
		printf("%lld\n",f[1][1]);
	}
	return 0;
}