SSLOJ1531 斐波拉契数列IV

发现以后离开了母校不一定能够上得了题库{因为内网才能上

所以以后SSLOJ都贴一下题目:

Description

求数列f[n]=f[n-2]+f[n-1]+n+1的第N项,其中f[1]=1,f[2]:=1.

Input

N(1<N<2^31-1)

Output

第n项结果 mod 9973


最开始推了两页纸最终只推出来一条感觉很没用的式子:f[n]=S(n-2)+1+(n+5)(n-2)/2

然而感觉这东西什么用都没有。开root去看了别人的程序结果看不懂= =

最终突然想出来了写了一个和别人完全不一样的东西A了= =果然自己思考才是比较好的选择

fn-1                      1 1 1 1                                 fn

fn-2                      1 0 0 0                                 fn-1

n              *           0 0 1 1              =                 n+1

1                          0 0 0 1                                  1

然后把中间那个矩阵算n-3次方用最开始的矩阵乘上就行

然而别人的矩阵都是n-2次方的快速幂= =难道我的不是比较正常的写法?

Problem Id:1531  User Id:BPM136 
Memory:1380K  Time:0MS
Language:G++  Result:Accepted

#include
#include
#include
#include
#include
#include
#define LL long long
#define fo(i,a,b) for(int i=a;i<=b;i++)
using namespace std;
LL read()
{
	LL d=0,f=1;char s=getchar();
	while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
	while(s>='0'&&s<='9'){d=d*10+s-'0';s=getchar();}
	return d*f;
}
#define N 4
#define inf 9973
struct matrix
{
	int a[N][N];
	void clear()
	{
		memset(a,0,sizeof(a));
	}
	matrix operator*(const matrix b)
	{
		matrix anss;
		fo(i,0,N-1)
		fo(j,0,N-1)
		{
			anss.a[i][j]=0;
			fo(k,0,N-1)
			{
				anss.a[i][j]+=a[i][k]*b.a[k][j];
				anss.a[i][j]%=inf;
			}
		}
		return anss;
	}
};
matrix I=
{
	1,0,0,0,
	0,1,0,0,
	0,0,1,0,
	0,0,0,1
};
matrix A=
{
	1,1,1,1,
	1,0,0,0,
	0,0,1,1,
	0,0,0,1
};
int n,m;

matrix KSM(matrix a,int b)
{
	if(b==0)return I;
	if(b==1)return A;
	matrix ret=KSM(a,b/2);
	ret=ret*ret;
	if(b%2)ret=ret*a;
	return ret;
}

int main()
{
	n=read();
	matrix ans;
	ans.a[0][0]=1;ans.a[1][0]=1;ans.a[2][0]=3;ans.a[3][0]=1;
	ans=KSM(A,n-3)*ans;
	LL anss=0;
	fo(i,0,N-1)anss+=ans.a[i][0];
	anss%=inf;cout<


你可能感兴趣的:(数论)