矩阵快速幂

1605: 数字序列

时间限制: 1 Sec  内存限制: 60 MB
提交: 819  解决: 191
[提交][状态][讨论版][命题人:541307010108]

题目描述

一个数列的定义如下:

f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.

给出A和B,你要求出f(n).

输入

输入包含多个测试案例。每个测试用例包含3个整数A,B和n在一行(1<=A,B≤1000,1≤n≤100000000)。

当输入三个0表示结束

输出

对于每个测试案例,输出f(n),单独占一行。

样例输入

1 1 3
1 2 10
0 0 0

样例输出

2
5

AC:代码

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;

const int maxn = 2;
#define mod 7


struct martix{
	int s[2][2];
};

martix mulmartix(martix a,martix b)
{
	martix temp;
	memset(temp.s,0,sizeof(temp.s));
	for(int i = 0;i<maxn;i++){
		for(int j = 0;j<maxn;j++){
			for(int k = 0;k<maxn;k++){
				temp.s[i][j] += a.s[i][k] * b.s[k][j];
				temp.s[i][j] = temp.s[i][j]%mod;
			}
		}
	}
	return temp;
}

martix powmartix(martix x,int b){
	martix a;
	memset(a.s,0,sizeof(a.s));
	for(int i = 0;i<maxn;i++){
		a.s[i][i] = 1;
	}
	while(b){
		if(b&1) a = mulmartix(x,a);
		b >>= 1;
		x = mulmartix(x,x);
	}
	return a;
}

int main()
{
	int a,b,n;
	while(~scanf("%d %d %d",&a,&b,&n))
	{
		if(a==0&&b==0&&n==0) break;
		martix x;
		x.s[0][0] = a;
		x.s[0][1] = b;
		x.s[1][0] = 1;
		x.s[1][1] = 0;
		martix y = powmartix(x,n-1);
		printf("%d\n",(y.s[1][0]%mod + y.s[1][1]%mod + mod )%mod);
	}
	
	return 0;
}

这个题还有简单版的参见我的博客:QAQ

优秀博客:博客一博客二

posted @ 2018-05-16 17:36  Nlifea  阅读(136)  评论(0编辑  收藏  举报