#矩阵乘法+龟速乘# [luogu P2044] [NOI2012]随机数生成器

Title

P2044 [NOI2012]随机数生成器


Solution

其实是一个等比数列,可以直接用通项公式。

但是复习了一下矩阵乘法,然后知道了如何正确的构造矩阵乘法中的中间矩阵,之前都是通过不停尝试来构造的。。。

以斐波那契数列为例

f[n]f[n-1]
f[n-1]10
f[n-2]11

因为 f [ n ] = f [ n − 1 ] + f [ n − 2 ] f[n]=f[n-1]+f[n-2] f[n]=f[n1]+f[n2],所以在第一列都填 1 1 1


所以这道题的中间矩阵

a0
11

因为乘法可能会爆 l o n g   l o n g long\ long long long,所以要用龟速乘。


Code

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#define ll long long 
#define rep(i,x,y) for(int i=x;i<=y;i++) 
using namespace std; 
const ll N=3; 
ll mod,n,g; 
ll tss(ll x,ll y){
	ll cnt=0; 
	for(;y;y>>=1){
		if (y&1) cnt=(cnt+x)%mod; 
		x=(x*2)%mod; 
	} 
	return cnt; 
}
struct Matrix{
	ll w,a[N][N],b[N][N],c[N][N]; 
	void mull(){
		memset(c,0,sizeof(c)); 
		rep(i,0,w-1) rep(j,0,w-1) rep(k,0,w-1) c[i][j]=(c[i][j]+tss(a[i][k],a[k][j])%mod)%mod; 
		memcpy(a,c,sizeof(c)); 
	}
	void mul(){
		memset(c,0,sizeof(c)); 
		rep(i,0,w-1) rep(j,0,w-1) rep(k,0,w-1) c[i][j]=(c[i][j]+tss(b[i][k],a[k][j])%mod)%mod; 
		memcpy(b,c,sizeof(c)); 
	}
}M;
ll read(){
	ll p=0; char c=getchar(); 
	while (!isdigit(c)) c=getchar(); 
	while (isdigit(c)) p=(p<<3)+(p<<1)+c-48,c=getchar(); 
	return p; 
}
int main(){
	mod=read(),M.a[0][0]=read(),M.b[0][1]=read(),M.b[0][0]=read(),n=read(),g=read(); 
	M.w=2; M.a[1][0]=M.a[1][1]=1; 
	for(;n;n>>=1,M.mull()) if (n&1) M.mul(); 
	return 0&printf("%lld",M.b[0][0]%g); 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值