Problem Description
You've got an array a, consisting of n integers. The array elements are indexed from 1 to n. Let's determine a two step operation like that:
First we build by the array a an array s of partial sums, consisting of n elements. Element number i (1 ≤ i ≤ n) of array s equals
. The operation x mod y means that we take the remainder of the division of number x by number y.
Then we write the contents of the array s to the array a. Element number i (1 ≤ i ≤ n) of the array s becomes the i-th element of the array a (ai = si).
You task is to find array a after exactly k described operations are applied.Input
The first line contains two space-separated integers n and k (1 ≤ n ≤ 2000, 0 ≤ k ≤ 109). The next line contains n space-separated integers a1, a2, ..., an — elements of the array a (0 ≤ ai ≤ 109).
Output
Print n integers — elements of the array a after the operations are applied to it. Print the elements in the order of increasing of their indexes in the array a. Separate the printed numbers by spaces.
Examples
Input
3 1
1 2 3Output
1 3 6
Input
5 0
3 14 15 92 6Output
3 14 15 92 6
题意:给出 n 个数,进行 k 次操作,每次操作将数组用其前缀数组代替,然后模 1E9+7,问 k 次操作后每个数的值
思路:矩阵快速幂
假设数组长度为 3,每一项为 a1、a2、a3
则有操作矩阵:
,其中,每一列的和为第 i 次操作的第 j 项
可以看出,题目实质是要求对矩阵 做 k 次乘法,使用矩阵快速幂即可解决
但由于裸的矩阵快速幂时间复杂度为 O(n*n*n*logk),无疑会 TLE,需要利用矩阵本身的性质来进行压缩,以降低时间复杂度
观看可以发现,每条与主对角线平行的斜线上的值是相等的,因此对于整个矩阵来说,真正有意义的值只是最上面的一行,故而可以将矩阵压缩成一个 1*n 的矩阵,然后对其进行矩阵快速幂
Source Program
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<bitset>
#define EPS 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD = 1E9+7;
const int N = 5000+5;
const int dx[] = {-1,1,0,0,-1,-1,1,1};
const int dy[] = {0,0,-1,1,-1,1,-1,1};
using namespace std;
struct Matrix{
LL s[N];//1*n的矩阵
};
Matrix e;//单位矩阵E
Matrix x;//构造矩阵x
LL a[N];
Matrix mul(Matrix A,Matrix B,LL n){//矩阵乘法
Matrix temp;//临时矩阵,存放矩阵A*矩阵B的结果
for(int i=1;i<=n;i++)
temp.s[i]=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=i;j++)
temp.s[i]=(temp.s[i]+(A.s[j]*B.s[i-j+1])%MOD)%MOD;
return temp;
}
Matrix quickPower(Matrix A,LL k,LL n){//矩阵快速幂
Matrix res=e;
while(k){
if(k&1)
res=mul(A,res,n);//res=A*e
A=mul(A,A,n);//A=A*A
k>>=1;
}
return res;
}
int main(){
LL n,k;
scanf("%lld%lld",&n,&k);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
//单位矩阵的第一行
for(int i=1;i<=n;i++)
e.s[i]=0;
e.s[1]=1;
//构造矩阵初始值
for(int i=1;i<=n;i++)
x.s[i]=1;
Matrix res=quickPower(x,k,n);//k次幂
for(int i=1;i<=n;i++){
LL val=0;
for(int j=1;j<=i;j++)
val=(val+a[i-j+1]*res.s[j])%MOD;
printf("%lld ",val);
}
printf("\n");
return 0;
}