12931ZZ

这篇博客介绍了ZZ函数,它在2013年ACM-ICPC泰国全国编程竞赛中出现。ZZ函数定义为给定四个整数a, b, c, d,计算ZZ(c, d)。问题涉及高精度计算,包括矩阵乘法、二分幂以及逆元的概念。作者提供了高效的算法实现,通过预处理n!的逆元,使用矩阵快速幂方法来解决复杂计算,并给出了样例输入和输出。
摘要由CSDN通过智能技术生成

ZZ
Problem description
ZZ-function, a shorter name of ZeedZaad-function is defines as followed.

Given 4 inegers a, b, c and d, your task is to find ZZ(c, d)

Input
First line of input is a number of test cases T ≤ 200.

Each test case is a line containing of 4 integers a, b, c and d (0 ≤ a, b ≤ 1 000 000 000, 1 ≤ c ≤ 100, 1 ≤ c x d ≤ 100 000 000)

Output
For each test case, display ZZ(c, d) mod 1 000 000 009.

Sample Input
5
1 1 1 1
1 1 1 4
1 1 2 3
1 1 5 5
24995 8633 1 25158567

Sample Output
1
7
7
155
512203519

Problem Source

2013 ACM-ICPC Thailand National Programming Contest

#include <stdio.h>
#define INT __int64
#define M 1000000009
int InvFact[100];//预处理n!的逆元

void ProductOfMatrix(int a[2][2],int b[2][2],int c[2][2]){
//矩阵乘法,a*b=c,但是矩阵大小是2*2的
	int i,j,k,d[2][2];
	INT t;
    for(i=0;i<2;i++){
		for(j=0;j<2;j++){
       		t=0LL;
       		for(k=0;k<2;k++){
         	t+=1LL*a[i][k]*b[k][j];
         }
       		d[i][j]=t%M;
	}
}
	for(i=0;i<2;i++)
		for(j=0;j<2;j++)
			c[i][j]=d[i][j];
}

int Power(int a,int b){     //二分计算a的b次方%M
INT t=1LL,T=a%M;
	while(b){
		if(b&1)t=t*T%M;
		T=T*T%M;
		b>>=1;
	}
	return t;
}	

void PowerOfMatrix(int k,int b[2][2]){
//二分法求递推矩阵的k次幂
		int a[2][2];
		a[0][0]=a[0][1]=a[1][0]=b[0][0]=b[1][1]=1;
		a[1][1]=b[0][1]=b[1][0]=0;
		while(k){
			if(k&1)ProductOfMatrix(a,b,b);
			k>>=1;
			ProductOfMatrix(a,a,a);
		}	
}

int ZZ0(int a,int b,int k){
//求初始值为a,b时的ZZ(0,k)
	int c[2][2];INT t;	
	if(k==1)return a;
	if(k==2)return b;
	PowerOfMatrix(k-2,c);
	t=(1LL*c[0][0]*b+1LL*c[0][1]*a)%M;
	return t;
} 

int Solve(int a,int b,int c,int d){
//函数计算初值为a,b时 ZZ(c,d)的值
	int t1=ZZ0(a,b,d+2*c);
	INT t2=0,t=1;
	int i;
	for(i=0;i<c;i++){
		t2=(t2+((ZZ0(a,b,(c-i)<<1)*t)%M)*InvFact[i])%M;
		t=t*(d+i)%M;
	}
	t1-=t2;
	if(t1<0)t1=t1+M;
	return t1;
}

int main()
{
	int i,t,a,b,c,d;
	InvFact[0]=InvFact[1]=1;
	//预处理出n!关于M的逆元,逆元的含义、求法要自己取找。目前只需要记住,一个数和它的逆元相乘结果取模后是1. 
	//InvFact[n]存储的元素就是n!的逆元 
	for(i=2;i<100;i++) InvFact[i]=(1LL*InvFact[i-1]*Power(i,M-2))%M;
    scanf("%d",&t);
    while(t--){
    	scanf("%d%d%d%d",&a,&b,&c,&d);
    	printf("%d\n",Solve(a,b,c,d));
    }
    return 0;
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值