0%

HDU 5171 GTY's birthday gift 矩阵快速幂

GTY’s birthday gift

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)

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次,然后求其总和。

分析

扩展规则很简单,就是一个斐波那契数列,但是如果按照模拟的方法手动推算,复杂度对于本题的数据范围来说是不太合适的。

可以利用矩阵快速幂来迅速完成。

$$\begin{bmatrix}S_{n-1}&F_n&F_{n-1}\end{bmatrix}*\begin{bmatrix}1&0&0\\1&1&1\\1&1&0\end{bmatrix}=\begin{bmatrix}S_n&F_{n+1}&F_n\end{bmatrix}$$

剩下要注意的就是数据范围要开到long long了,因为可能涉及到$10^9 * 10^9$这样的数量级。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/* ***********************************************
MYID : Chen Fan
LANG : G++
PROG : HDU5171
************************************************ */

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

#define MOD 10000007

using namespace std;

typedef struct matrixnod
{
long long m[3][3];
} matrix;

matrix ex=
{
1,0,0,
1,1,1,
1,1,0
};

matrix mat(matrix a,matrix b)
{
matrix c;
for (int i=0;i<3;i++)
for (int j=0;j<3;j++)
{
c.m[i][j]=0;
for (int k=0;k<3;k++) c.m[i][j]+=(a.m[i][k]*b.m[k][j])%MOD;
c.m[i][j]%=MOD;
}
return c;
}

matrix mat2(matrix a,matrix b)
{
matrix c;
for (int j=0;j<3;j++)
{
c.m[0][j]=0;
for (int k=0;k<3;k++) c.m[0][j]+=(a.m[0][k]*b.m[k][j])%MOD;
c.m[0][j]%=MOD;
}
return c;
}

matrix doexpmat(matrix b,int n)
{
matrix a=
{
1,0,0,
0,1,0,
0,0,1
};
while(n)
{
if (n&1) a=mat(a,b);
n=n>>1;
b=mat(b,b);
}
return a;
}

int main()
{
int n,k;
int a[100010];
while(scanf("%d%d",&n,&k)==2)
{
long long sum=0;
for (int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
sum=(sum+a[i])%MOD;
}
sort(&a[1],&a[n+1]);
matrix start;
start.m[0][0]=0;
start.m[0][1]=a[n];
start.m[0][2]=a[n-1];
start=mat2(start,doexpmat(ex,k));

sum=(sum+start.m[0][0])%MOD;
printf("%lld\n",sum);
}

return 0;
}