矩阵快速幂(hdu5171GTY's birthday gift)

来源:互联网 发布:客户关怀软件 编辑:程序博客网 时间:2024/06/03 12:30

GTY's birthday gift

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


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 23 6 2
 

Sample Output
35
 

Source
BestCoder Round #29

每次挑选两个最大的进行加和,然后放到集合里

构造矩阵

     | 0  1  0 |

A=| 1  1  0 |

     | 1  1  1 |

     | a |

B=| b |

     | a+b |

其中a代表集合中第二大,b代表最大

A^k*B的最后一项加上集合中除去a,b其他元素的和就是答案

#include<iostream>#include<cstdio>#include<string>#include<cstring>#include<vector>#include<cmath>#include<queue>#include<stack>#include<map>#include<set>#include<algorithm>using namespace std;typedef long long LL;const int maxn=100010;const int maxm=5;const int MOD=10000007;int N,a[maxn],K;struct Matrix{    LL mat[maxm][maxm];    Matrix(){memset(mat,0,sizeof(mat));}    Matrix operator * (Matrix A)    {        Matrix res;        for(int i=0;i<3;i++)        {            for(int j=0;j<3;j++)            {                for(int k=0;k<3;k++)                    res.mat[i][j]=(res.mat[i][j]+(mat[i][k]*A.mat[k][j])%MOD)%MOD;            }        }        return res;    }};Matrix pow_mul(Matrix A,int n){    Matrix res;    for(int i=0;i<maxm;i++)res.mat[i][i]=1;    while(n)    {        if(n&1)res=res*A;        A=A*A;        n>>=1;    }    return res;}int main(){    while(scanf("%d%d",&N,&K)!=EOF)    {        for(int i=1;i<=N;i++)scanf("%d",&a[i]);        sort(a+1,a+1+N);        Matrix A,B;        A.mat[0][1]=A.mat[1][0]=A.mat[1][1]=A.mat[2][0]=A.mat[2][1]=A.mat[2][2]=1;        A=pow_mul(A,K);        B.mat[0][0]=a[N-1],B.mat[1][0]=a[N],B.mat[2][0]=a[N-1]+a[N];        A=A*B;        LL sum=0;        for(int i=1;i<N-1;i++)sum+=a[i];        sum=(sum+A.mat[2][0])%MOD;        printf("%I64d\n",sum);    }    return 0;}




0 0
原创粉丝点击