标签:
GTY‘s birthday gift
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 225 Accepted Submission(s): 78
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,b∈S),
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 (2≤n≤100000,1≤k≤1000000000).
The second line contains n elements ai (1≤ai≤100000)separated
by spaces , indicating the multiset S .
Output
For each case , print the maximum sum of the multiset (mod 10000007).
Sample Input
Sample Output
Source
从n个数中,选两个数求和,然后加入这n个数,如此进行k次,求这n个数和后来加的数的和最大。
从给定的数组中选取次大的数为a,最大的数是b,如果要使得最终答案最大,那么下面的数分别就是a+b,a+2*b,2*a+3*c,3*a+5*c,5*a+8*c
a的系数分别是1 1 2 3 5
b的系数分别是1 2 3 5 8
a的系数很明显是斐波那契数列,b的系数在最开始补一个1也是斐波那契数列,因此可以用矩阵快速幂求得第n项a的系数和b的系数,但是问题求得是这些数的和,而不是求第n项是几。
求斐波那契数列的前n项有一个公式:S(n)=a(n+2)-1。因此求得第n+2项斐波那契数列就可以了,然后分别乘以a和b,就是答案。
注意b的系数多补了第一项1,所以最后还要多减去1。
//124MS 1900K
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#define mod 10000007
#define ll __int64
using namespace std;
ll s[100007];
struct Matrax
{
ll m[2][2];
}a,per,tmp;
void init()//建立矩阵
{
a.m[0][0]=1;a.m[0][1]=1;
a.m[1][0]=1;a.m[1][1]=0;
per.m[0][0]=1;per.m[0][1]=0;
per.m[1][0]=0;per.m[1][1]=1;
}
Matrax multi(Matrax a,Matrax b)//矩阵相乘
{
Matrax c;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
{
c.m[i][j]=0;
for(int k=0;k<2;k++)
c.m[i][j]=(c.m[i][j]+a.m[i][k]*b.m[k][j])%mod;//比赛的时候漏了%mod
}
return c;
}
Matrax power(ll k)//矩阵快速幂
{
Matrax pp=a,ans=per;
while(k)
{
if(k&1){ans=multi(ans,pp);k--;}
else {k>>=1;pp=multi(pp,pp);}
}
return ans;
}
int main()
{
ll n,k;
while(scanf("%I64d%I64d",&n,&k)!=EOF)
{
init();
ll sum=0,aa,bb,c;
for(int i=0;i<n;i++)
{
scanf("%I64d",&s[i]);
sum=(sum+s[i])%mod;
}
sort(s,s+n);
aa=s[n-2];bb=s[n-1];
Matrax ans1=power(k+2);//求a系数的第n+2项斐波那契数列
Matrax ans2=power(k+3);//求b系数的第n+2项斐波那契数列,因为补了一个1,所以是k+3
ll f=(ans1.m[0][1]-1+mod)%mod;
ll e=(ans2.m[0][1]-2+mod)%mod;//最后多减去补得1
sum=(sum+f*aa)%mod;
sum=(sum+e*bb)%mod;
printf("%I64d\n",sum);
}
return 0;
}
HDU 5171 GTY's birthday gift 矩阵快速幂
标签:
原文地址:http://blog.csdn.net/crescent__moon/article/details/43617703