HDU 5171(矩阵快速幂)

GTY's birthday gift

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 567    Accepted Submission(s): 238


Problem Description
FFZ's birthday is coming. GTY wants to give a gift to ZZF. He asked his gay friends what he should give to ZZF. One of them said, 'Nothing is more interesting than a number multiset.' So GTY decided to make a multiset for ZZF. Multiset can contain elements with same values. Because GTY wants to finish the gift as soon as possible, he will use JURUO magic. It allows him to choose two numbers a and b( a,bS ), and add  a+b  to the multiset. GTY can use the magic for k times, and he wants the sum of the multiset is maximum, because the larger the sum is, the happier FFZ will be. You need to help him calculate the maximum sum of the multiset.
 

Input
Multi test cases (about 3) . The first line contains two integers n and k ( 2n100000,1k1000000000 ). The second line contains n elements  ai  ( 1ai100000 )separated by spaces , indicating the multiset S .
 

Output
For each case , print the maximum sum of the multiset ( mod 10000007 ).
 

Sample Input
   
   
   
   
3 2 3 6 2
 

Sample Output
   
   
   
   
35
 

Source
BestCoder Round #29
 

题意:大概就是叫你求斐波那契数列的前n项和

分析:Sn=Sn-1+Fn,Fn=Fn-1+Fn-2,利用矩阵快速幂求出前n项和,转移矩阵为:
                                  
[Sn-1  Fn-1  Fn-2]  * [ ... ]   =  [Sn Fn Fn-1],中间那个为3*3矩阵,这...不太好写。。自己很容易求。。
发现对于有递推关系的用矩阵快速幂不错。觉得还是有点神奇的,只要构造一个矩阵便可。
                       
#include<stdio.h>
#include<string.h>
#define mod 10000007
typedef long long ll;
struct Mat
{
    ll mat[5][5];
};

Mat operator * (Mat a, Mat b)
{
    Mat c;
    memset(c.mat, 0, sizeof(c.mat));
    for(int k=0; k<3; k++)
        for(int i=0; i<3; i++)
            for(int j=0; j<3; j++)
                c.mat[i][j] = (c.mat[i][j]+a.mat[i][k]*b.mat[k][j])%mod;
    return c;
}

int main()
{
    int n, k;
    Mat a, res;

    while(~scanf("%d%d", &n,&k))
    {
        ll f1 = -1, f2 = -1, f, sum=0;
        for(int i=0; i<n; i++)
        {
            scanf("%lld", &f);
            sum += f;
            if(f > f1) f2 = f1, f1 = f;
            else if(f > f2) f2 = f;
        }//f1,f2为初始值
        sum = sum-f1-f2;
        a.mat[0][0]=1; a.mat[0][1] = a.mat[0][2]=0;
        a.mat[1][0] = a.mat[1][1] = a.mat[1][2] = 1;
        a.mat[2][0] = a.mat[2][1] = 1; a.mat[2][2] = 0;
        for(int i=0; i<3; i++)
            for(int j=0; j<3; j++)
                res.mat[i][j] = (i==j); //初始为单位矩阵
        for(; k>0; k>>=1) //快速幂
        {
            if(k & 1) res = res*a;
            a = a*a;
        }
        sum += (f1+f2)*res.mat[0][0]+f1*res.mat[1][0]+f2*res.mat[2][0];
        printf("%lld\n", sum%mod);
    }
    return 0;
}


你可能感兴趣的:(矩阵快速幂)