GTY's birthday gift
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1282 Accepted Submission(s): 501
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
3 2 3 6 2
Sample Output
35
问k次操作之后集合里的数之和为多少,结果对10000007取模
思路:可以发现其实这就是一个斐波那契的问题,斐波那契的第一项和第二项是初始集合里最大的两个数
因为k有10亿 所以考虑不能朴素算法, 于是我们考虑写出特征矩阵,然后用矩阵快速幂
那么这里问题来了,如果是要求F(n),那很简单,可是要求和怎么办? 我们可以考虑写一个3*3的矩阵,一维用来维护和
Sn (1 1 0)Sn-1
Fn+1(0 1 1)Fn
Fn (0 1 0)Fn-1
那么有Sn=Sn-1+Fn
Fn=Fn-1+Fn-2 就可以直接转移了
注意这里右边是Fn,所以我们最后需要进行k+1次操作~
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
#define N 100050
#define mod 10000007
long long a[N];
int n;
long long sum;
struct Matrix
{
long long ma[3][3];
};
Matrix mul(Matrix A,Matrix B)
{
Matrix C;
memset(C.ma,0,sizeof(C.ma));
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
for(int k=0; k<3; k++)
C.ma[i][j]=(C.ma[i][j]+A.ma[i][k]*B.ma[k][j])%mod;
return C;
}
Matrix pow_mod(Matrix A,long long n)
{
Matrix B;
memset(B.ma,0,sizeof(B.ma));
B.ma[0][0]=B.ma[1][1]=B.ma[2][2]=1;
while(n)
{
if(n&1) B=mul(B,A);
A=mul(A,A);
n>>=1;
}
return B;
}
int main()
{
long long k;
while(~scanf("%d %lld",&n,&k))
{
sum=0;
for(int i=0; i<n; i++)
{
scanf("%lld",&a[i]);
sum=(sum+a[i])%mod;
}
sort(a,a+n);
Matrix A;
memset(A.ma,0,sizeof(A.ma));
A.ma[0][0]=A.ma[0][1]=A.ma[1][1]=A.ma[1][2]=A.ma[2][1]=1;
Matrix ans=pow_mod(A,k+1);
sum-=a[n-1];
sum-=a[n-2];
long long m=(ans.ma[0][0]*a[n-2]+ans.ma[0][1]*a[n-1]+ans.ma[0][2]*a[n-2])%mod;
printf("%lld\n",(sum+m)%mod);
}
return 0;
}