You are given a list of numbers A1 A2 .. AN and M queries. For the i-th query:
You task is to calculate Fi(Ri) for each query. Because the answer can be very large, you should output the remainder of the answer divided by 1000000007.
There are multiple test cases. The first line of input is an integer T indicates the number of test cases. For each test case:
The first line contains two integers N, M (1 <= N, M <= 100000). The second line contains N integers A1 A2 .. AN (1 <= Ai <= 1000000000).
The next M lines, each line is a query with two integer parameters Li, Ri (1 <= Li <= Ri <= N).
For each test case, output the remainder of the answer divided by 1000000007.
1 4 7 1 2 3 4 1 1 1 2 1 3 1 4 2 4 3 4 4 4
1 2 5 13 11 4 4题意:
定义了一种序列。求序列的第n项。
思路:
关键是构成矩阵。
[f[n-2] f[n-1]]*?=[f[n-1] f[n]]
由观察法可得目标矩阵为
|0 A[n]|
|1 1|
所以就是线段树维护矩阵乘积了。
详细见代码:
#include<stdio.h> #include<iostream> using namespace std; typedef long long ll; const int mod=1e9+7; const int maxn=100010; #define lson L,mid,ls #define rson mid+1,R,rs struct Matrix { int row,col; ll val[2][2]; Matrix(int r=2,int c=2) { row=r,col=c; for(int i=0;i<row;i++) for(int j=0;j<col;j++) val[i][j]=0; } Matrix operator *(Matrix& mat) { Matrix tp; tp.row=row,tp.col=mat.col; for(int i=0;i<row;i++) for(int j=0;j<mat.col;j++) { for(int k=0;k<col;k++) tp.val[i][j]+=(val[i][k]*mat.val[k][j])%mod; tp.val[i][j]%=mod; } return tp; } } tree[maxn<<2]; int A[maxn]; void build(int L,int R,int rt) { if(L==R) { tree[rt].row=tree[rt].col=2; scanf("%d",&A[L]); tree[rt].val[0][0]=0; tree[rt].val[0][1]=A[L]; tree[rt].val[1][0]=tree[rt].val[1][1]=1; return ; } int ls=rt<<1,rs=ls|1,mid=(L+R)>>1; build(lson); build(rson); tree[rt]=tree[ls]*tree[rs]; } Matrix qu(int L,int R,int rt,int l,int r) { if(l<=L&&R<=r) return tree[rt]; int ls=rt<<1,rs=ls|1,mid=(L+R)>>1; Matrix tp,tt; tp.row=tp.col=2; tp.val[0][0]=tp.val[1][1]=1; if(l<=mid) tt=qu(lson,l,r),tp=tp*tt; if(r>mid) tt=qu(rson,l,r),tp=tp*tt; return tp; } int main() { int t,n,m,l,r,i; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&m); build(1,n,1); for(i=1;i<=m;i++) { scanf("%d%d",&l,&r); if(r-l<2) printf("%d\n",A[r]); else { Matrix tp=qu(1,n,1,l+2,r); ll ans=(A[l]*tp.val[0][1]%mod+A[l+1]*tp.val[1][1])%mod; printf("%d\n",(int)ans); } } } return 0; }
zoj 3772 Calculate the Function(线段树+矩阵乘法)
原文地址:http://blog.csdn.net/bossup/article/details/45222411