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).
OutputFor each test case, output the remainder of the answer divided by 1000000007.
Sample Input1 4 7 1 2 3 4 1 1 1 2 1 3 1 4 2 4 3 4 4 4Sample Output
1 2 5 13 11 4 4
#include<stdio.h>
#include<string.h>
#include<vector>
#include<iostream>
#include<algorithm>
#define ls(x) (x<<1)
#define rs(x) (x<<1|1)
using namespace std;
typedef long long ll;
const int mod=1e9+7;
const int maxn=1e5+10;
int n,m;
/*
忘了线段树这个优美的结构了,这道题,当时真是可惜,在自己的能力范围内,但是没有做出来
当时,我想了一下线段树,但是很快就又跳了过去,主要是考虑到复杂度,不知道当时自己怎么想的
感觉就是会超,它是一个log(n)的复杂度,是没有问题的
*/
struct Martix{
ll mar[3][3];
Martix operator *(const Martix &b){
Martix c;
for(int i=1;i<=2;i++){
for(int j=1;j<=2;j++){
c.mar[i][j]=0;
for(int k=1;k<=2;k++){
c.mar[i][j]=(c.mar[i][j]+mar[i][k]*b.mar[k][j]%mod)%mod;
}
}
}
return c;
}
};
struct node{
Martix m;
int l,r;
}tr[maxn*4];
ll val[maxn];
void build(int l,int r,int o){
tr[o].l=l,tr[o].r=r;
if(l==r){
tr[o].m.mar[1][1]=1;
tr[o].m.mar[2][1]=1;
tr[o].m.mar[1][2]=val[n-l+1];
tr[o].m.mar[2][2]=0;
return ;
}
int mid=(l+r)>>1;
build(l,mid,ls(o));
build(mid+1,r,rs(o));
tr[o].m=tr[ls(o)].m*tr[rs(o)].m;
}
Martix query(int l,int r,int o){
if(tr[o].l>=l&&tr[o].r<=r)
return tr[o].m;
int mid=(tr[o].l+tr[o].r)>>1;
if(r<=mid)
return query(l,r,ls(o));
else if(l>mid)
return query(l,r,rs(o));
else
return query(l,mid,ls(o))*query(mid+1,r,rs(o));
}
int main()
{
int T;
scanf("%d",&T);
while(T--){
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++){
scanf("%lld",&val[i]);
}
build(1,n,1);
for(int i=1;i<=m;i++){
int l,r;
scanf("%d %d",&l,&r);
if(r-l<2){
printf("%lld\n",val[r]);
}
else{
Martix m=query(n-r+1,n-l-1,1);
ll ans=(val[l+1]*m.mar[1][1]+val[l]*m.mar[1][2]%mod+mod)%mod;
printf("%lld\n",ans);
}
}
}
return 0;
}
本文介绍了一种结合线段树和矩阵快速幂的方法来解决特定查询问题。通过构造特殊的线段树结构,实现对区间内定义的递推序列进行高效计算。此方法适用于处理大量区间查询,尤其当答案可能非常大时,采用取模操作确保数值在合理范围内。
435

被折叠的 条评论
为什么被折叠?



