HDU5950Recursive sequence(构造矩阵+矩阵乘法)

来源:互联网 发布:mac不能无线键盘 编辑:程序博客网 时间:2024/06/08 09:39

题目大意:

求 f(n) = f(n1)+2f(n2)+n4,其中 f(1)=a,f(2)=b



思路:http://m.blog.csdn.net/chen_ze_hua/article/details/52973395

首先一看这个题目,很容易想到构造矩阵:那么我们现在来分析一下怎么构造这个矩阵,那么 (n+1)4 = n4+4n3+6n2+4n+1 所以光 (n+1)4 这个矩阵就能构造出 55 的一个矩阵来, 然后 f(n) = f(n1)+2f(n2) 这个是 22 的矩阵,所以构造出来就应该是 77 的转移矩阵 A : 
{f(n),f(n1),n4,n3,n2,n,1}A={f(n+1),f(n),(n+1)4,(n+1)3,(n+1)2,(n+1),1}

然后 f(n+1) = f(n)+2f(n1)+(n+1)4, 可得矩阵 A 

1214641100000000146410001331000012100000110000001

然后 f(n+1) = {{f(n),f(n1),n4,n3,n2,n,1}An2}.mat[0][0]


C0400000C04C14C030000C14C24C13C02000C24C34C23C12C0100C34C44C33C22C11C000C4400000020000011

#include<bits/stdc++.h>using namespace std;typedef long long ll;const ll mod = 2147493647;struct Matrix{    int r, c;    ll mat[7][7];};ll mat[7][7]={ {1, 4, 6, 4, 1, 0, 0}, {0, 1, 3, 3, 1, 0, 0}, {0, 0, 1, 2, 1, 0, 0}, {0, 0, 0, 1, 1, 0, 0}, {0, 0, 0, 0, 1, 0, 0}, {0, 0, 0, 0, 0, 0, 1}, {1, 4, 6, 4, 1, 2, 1}};Matrix mul(Matrix a, Matrix b){    Matrix ret;    ret.r = a.r;    ret.c = b.c;    for(int i = 0; i < ret.r; i++)        for(int j = 0; j < ret.c; j++)        {            ret.mat[i][j] = 0;            for(int k = 0; k < a.c; k++)            {                ret.mat[i][j] += a.mat[i][k] * b.mat[k][j];                ret.mat[i][j] %= mod;            }        }    return ret;}Matrix quick_pow(Matrix a, ll b){    Matrix ret;    ret.r = ret.c = 7;    memset(ret.mat, 0, sizeof(ret.mat));    for(int i = 0; i < 7; i++)        ret.mat[i][i] = 1;    while(b)    {        if(b&1)            ret = mul(ret, a);        a = mul(a, a);        b >>= 1;    }    return ret;}int main(){    int t;    scanf("%d", &t);    while(t--)    {        ll n, a, b;        scanf("%I64d%I64d%I64d", &n, &a, &b);        if(n == 1) printf("%I64d\n", a);        else if(n == 2) printf("%I64d\n", b);        else        {            Matrix temp;            temp.r = temp.c = 7;            memcpy(temp.mat, mat, sizeof(mat));            Matrix ret = quick_pow(temp, n-2);            temp.r = 7;temp.c = 1;            temp.mat[0][0] = 16,temp.mat[1][0] = 8,temp.mat[2][0] = 4,temp.mat[3][0] = 2,temp.mat[4][0] = 1,temp.mat[5][0] = a%mod, temp.mat[6][0] = b%mod;            ret = mul(ret, temp);            printf("%I64d\n", ret.mat[6][0]);        }    }    return 0;}








原创粉丝点击