You are given a list of numbers A1 A2 .. AN and M queries. For the i-th query:
- The query has two parameters Li and Ri.
- The query will define a function Fi(x) on the domain [Li, Ri] ∈ Z.
- Fi(Li) = ALi
- Fi(Li + 1) = A(Li + 1)
- for all x >= Li + 2, Fi(x) = Fi(x - 1) + Fi(x - 2) × Ax
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.
Input
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).
Output
For each test case, output the remainder of the answer divided by 1000000007.
Sample Input
1 4 7 1 2 3 4 1 1 1 2 1 3 1 4 2 4 3 4 4 4
Sample Output
1 2 5 13 11 4 4
Author: CHEN, Weijie
Source: The 14th Zhejiang University Programming Contest
题意:给一个序列An,有m个询问,每个询问包括l和r,定义f(l) = a[l], f(l+1) = a[l+1], f(x)=f(x-1) + a[x] * f(x-2), x >= l + 2;,对每个询问,求f(r)
解题思路:当x>=l+2时,f(x)=f(x-1) + a[x]* f(x-2), 所以就有递推式
所以当r>=l+1时,
用线段树来解决,每个节点保存一个矩阵
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
using namespace std;
#define LL long long
const LL mod=1e9+7;
LL a[100060];
int n,m;
struct node
{
LL xx[3][3];
node(){memset(xx,0,sizeof xx);}
}x[4*100060];
node Union(node a,node b)
{
node ans;
for(int i=1; i<=2; i++)
{
for(int j=1; j<=2; j++)
{
for(int k=1; k<=2; k++)
{
ans.xx[i][j]+=a.xx[i][k]*b.xx[k][j];
ans.xx[i][j]%=mod;
}
}
}
return ans;
}
void build(int l,int r,int k)
{
if(l==r)
{
x[k].xx[1][1]=x[k].xx[1][2]=1;
x[k].xx[2][1]=a[r+1];
x[k].xx[2][2]=0;
return ;
}
int mid=(l+r)>>1;
build(l,mid,k<<1);
build(mid+1,r,k<<1|1);
x[k]=Union(x[k<<1],x[k<<1|1]);
}
node query(int l,int r,int ll,int rr,int k)
{
if(ll>=l&&rr<=r) return x[k];
int mid=(ll+rr)>>1;
node ans;
ans.xx[1][1]=ans.xx[2][2]=1;
if(l<=mid) ans=Union(ans,query(l,r,ll,mid,k<<1));
if(r>mid) ans=Union(ans,query(l,r,mid+1,rr,k<<1|1));
return ans;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++) scanf("%lld",&a[i]);
memset(x,0,sizeof x);
build(1,n-1,1);
while(m--)
{
int l,r;
scanf("%d%d",&l,&r);
if(l==r) printf("%lld\n",a[l]);
else if(r==l+1) printf("%lld\n",a[r]);
else
{
node ans=query(l+1,r-1,1,n-1,1);
printf("%lld\n",(a[l]*ans.xx[2][1]+a[l+1]*ans.xx[1][1])%mod);
}
}
}
return 0;
}