F - Calculate the Function ZOJ 3772
Time Limit: 2000 MS Memory Limit: 65536 KB
64-bit integer IO format: %lld , %llu Java class name: Main
Description
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
思路:参考的别人的http://blog.csdn.net/john159151/article/details/24750443
刚开始想到了,但是没想到用线段树维护,于是悲剧了。。。
这样用线段树维护区间(l,r)的矩阵的乘积,用到的时候直接查询就行了
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn=100010;
const int MOD=1000000007;
int N,M;
int A[maxn];
struct Matrix
{
LL mat[2][2];
int x,y;
Matrix(int a=2,int b=2)
{
x=a,y=b;
memset(mat,0,sizeof(mat));
}
Matrix operator*(Matrix a)
{
Matrix res;
for(int i=0;i<x;i++)
{
for(int j=0;j<y;j++)
for(int k=0;k<y;k++)
res.mat[i][j]=(res.mat[i][j]+mat[i][k]*a.mat[k][j])%MOD;
}
return res;
}
};
struct IntervalTree
{
Matrix sum[maxn<<2];
void build(int o,int l,int r)
{
if(l==r)
{
sum[o].mat[0][0]=sum[o].mat[1][0]=1;
sum[o].mat[0][1]=A[l];
sum[o].mat[1][1]=0;
return ;
}
int mid=(l+r)>>1;
build(o<<1,l,mid);
build(o<<1|1,mid+1,r);
pushup(o);
}
void pushup(int o)
{
sum[o]=sum[o<<1|1]*sum[o<<1];
}
Matrix query(int o,int l,int r,int q1,int q2)
{
if(q1<=l&&r<=q2)return sum[o];
int mid=(l+r)>>1;
Matrix res;
res.mat[0][0]=res.mat[1][1]=1;
if(q2>mid)res=res*query(o<<1|1,mid+1,r,q1,q2);
if(q1<=mid)res=res*query(o<<1,l,mid,q1,q2);
return res;
}
}tree;
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&N,&M);
for(int i=1;i<=N;i++)scanf("%d",&A[i]);
tree.build(1,1,N);
while(M--)
{
int x,y;
scanf("%d%d",&x,&y);
if(y-x+1<=2)printf("%d\n",A[y]%MOD);
else
{
Matrix res=tree.query(1,1,N,x+2,y);
Matrix tmp;
tmp.mat[0][0]=A[x+1],tmp.mat[1][0]=A[x];
tmp.mat[0][1]=tmp.mat[1][1]=0;
res=res*tmp;
printf("%lld\n",res.mat[0][0]);
}
}
}
return 0;
}