F - Calculate the Function ZOJ - 3772

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
#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;
}

猜你喜欢

转载自blog.csdn.net/qq_36424540/article/details/80150396
ZOJ