HDU3411 Snail Alice【矩阵快速幂】

题意:,求f(n), q=x1^y1+z1, n=2^y2+z2 ,0<=x1,y1,z1,y2,z2<=50000


思路:推公式就算了,打个表,找规律,发现f(n) = (q-1)*f(n-1) + q * f(n-2),矩阵快速幂,我们要求一个矩阵的n-1次,n =2^y2+z2,y2可以达到几万,2^y2存不下,但是底数是2,2^y2相当于1个1后面跟了y2个0,把那个1减过来,就是连续的y2个1,模拟下y2个1的快速幂,再乘上矩阵的z2次方。


PS:如果没有把1减过来,减到z2这里,那就是模拟1个1后面跟了y2个0的快速幂,再乘上矩阵的z2 -1次方,但是会TLE,z2要是等于0,z2-1就是-1了,导致TLE。1减到y2那里就没有影响了,最坏情况就是0个1


#include<stdio.h>
#include<iostream>
#include<string.h>
#include<string>
#include<stdlib.h>
#include<math.h>
#include<vector>
#include<list>
#include<map>
#include<stack>
#include<queue>
#include<algorithm>
#include<numeric>
#include<functional>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int maxn = 5;

int MOD,N;
struct data
{
	ll s[maxn][maxn];
}res,tp,tp2;

void init(ll q)
{
	N = 2;
	memset(res.s,0,sizeof res.s);
	memset(tp.s,0,sizeof tp.s);
	res.s[1][1] = 1;res.s[2][2] = 1;
	tp.s[1][1] = q-1; tp.s[1][2] = q;
	tp.s[2][1] = 1;   tp.s[2][2] = 0;
	tp2.s[1][1] = q-1; tp2.s[1][2] = q;
	tp2.s[2][1] = 1;   tp2.s[2][2] = 0;
}

struct data mat(struct data &x,struct data &y)
{
	struct data temp;
	memset(temp.s,0,sizeof temp.s);
	for(int i = 1; i <= N; i++)
	{
		for(int j = 1; j <= N; j++)
		{
			for(int k = 1; k <= N; k++)
			{
				temp.s[i][j] = (temp.s[i][j] + x.s[i][k] * y.s[k][j]) % MOD;
			}
		}
	}
	return temp;
}

struct data mpow(struct data &a,ll b)
{
	while(b)
	{
		if(b&1) res = mat(res,a);
		b >>= 1;
		a = mat(a,a); 
	}
	return res;
}

ll kuai(ll a,ll b)
{
	ll res = 1;
	while(b)
	{
		if(b&1) res = res * a % MOD;
		b >>= 1;
		a = a * a % MOD;
	}
	return res;
}

int main(void)
{
	ll x1,y1,z1,y2,z2;
	while(scanf("%lld%lld%lld",&x1,&y1,&z1)!=EOF && (x1 != -1 || y1 != -1 || z1 != -1))
	{
		scanf("%lld%lld%d",&y2,&z2,&MOD);
		ll q = (kuai(x1,y1)+z1) % MOD;
		if(y2 == 0 && z2 == 0)
			printf("1\n");
		else
		{
			init(q);
			/*for(int i = 1; i <= y2; i++)  //TLE,z2 = 0 
				tp = mat(tp,tp);
			res = mat(res,tp);
			res = mpow(tp2,z2-1);*/
			for(int i = 1; i <= y2; i++)
			{
				res = mat(res,tp);
				tp = mat(tp,tp);
			}
			res = mpow(tp2,z2);
			printf("%lld\n",res.s[1][1]);
		}
	}
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值