幼儿园数学题Ⅰ【矩阵乘法】

>Link

ssl 2513


>Description

原题好像有点问题,实际就是求斐波那契数列中前 n n n项和


>解题思路

思路与斐波那契数列的和一样


>代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define LL long long
using namespace std;

const LL p = 1000000007;
struct matrix
{
    
    
	int x, y;
	LL a[10][10];
} A, B, ans;

matrix operator *(matrix a, matrix b)
{
    
    
	matrix c;
	c.x = a.x, c.y = b.y;
	for (int i = 1; i <= c.x; i++)
	  for (int j = 1; j <= c.y; j++) c.a[i][j] = 0;
	for (int k = 1; k <= a.y; k++)
	  for (int i = 1; i <= c.x; i++)
	    for (int j = 1; j <= c.y; j++)
	      c.a[i][j] = (c.a[i][j] + a.a[i][k] * b.a[k][j] % p) % p;
	return c;
}
void power (LL k)
{
    
    
	if (k == 1) {
    
    B = A; return;}
	power (k >> 1);
	B = B * B;
	if (k & 1) B = B * A; 
}

int main()
{
    
    
	LL n;
	scanf ("%lld", &n);
	if (n == 1) {
    
    printf ("1"); return 0;}
	A.x = 3, A.y = 3;
	A.a[1][2] = A.a[2][1] = A.a[2][2] = A.a[2][3] = A.a[3][3] = 1;
	power (n - 1);
	
	ans.x = 1, ans.y = 3;
	ans.a[1][1] = ans.a[1][2] = ans.a[1][3] = 1;
	ans = ans * B;
	printf ("%lld", ans.a[1][3]);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43010386/article/details/111399927