做法题目中已经给了,就是将

{ 1,1

   1,0}

这个矩阵自乘n次。连续自乘n次的话就没意思了,那还不如直接上Fibonacci递推公式呢。矩阵的魅力就在于它可以上快速幂。因为矩阵乘法满足结合律么……

代码:

program poj3070;//By_Thispoet
const
	mol=10000;
	fib:array[1..2,1..2]of longint=((1,1),(1,0));
type
	arr=array[1..2,1..2]of longint;
var
	n					:longint;
	ans					:arr;

function quickmi(p:longint):arr;
var tmp,quick:arr;
	i,j,k:longint;
begin
	if p=1 then exit(fib);
	tmp:=quickmi(p shr 1);
	fillchar(quick,sizeof(quick),0);
	for i:=1 to 2 do
		for j:=1 to 2 do
			for k:=1 to 2 do
				quick[i,j]:=(quick[i,j]+tmp[i,k]*tmp[k,j])mod mol;
	if p and 1=1 then
		begin
			fillchar(tmp,sizeof(tmp),0);
			for i:=1 to 2 do
				for j:=1 to 2 do
					for k:=1 to 2 do
						tmp[i,j]:=(tmp[i,j]+quick[i,k]*fib[k,j])mod mol;
			quick:=tmp;
		end;
	exit(quick);
end;

begin
	readln(n);
	while not (n=-1) do
		begin
			fillchar(ans,sizeof(ans),0);
			if n>1 then
				ans:=quickmi(n-1);
			if n=0 then ans[1,1]:=0;
			if n=1 then ans[1,1]:=1;
			writeln(ans[1,1]);
			readln(n);
		end;
end.

相关文章:

  • 2021-09-26
  • 2021-10-09
  • 2022-01-16
  • 2022-12-23
  • 2021-12-29
  • 2022-02-18
  • 2021-12-24
  • 2022-12-23
猜你喜欢
  • 2022-01-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-13
  • 2021-12-03
  • 2021-04-10
  • 2021-08-06
相关资源
相似解决方案