[題解]codeforces 718c Sasha and Array

Description

題目大意:
給定一個長度爲N的序列An ,要求支持區間加、區間求f(Ai) ,其中f(i) 表示斐波那契數列第i項。
N100000

Solution

線段樹,把斐波那契數列的轉移矩陣作爲標記,每次區間乘上轉移矩陣的幾次方即可。注意不能標記永久化,因爲矩陣乘法不符合交換律。
代碼:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

template<typename T>inline void read(T &x){
    T f=1;char ch=getchar();
    for(;ch<'0'||ch>'9';ch=getchar())if(ch=='-')f=-1;
    for(x=0;ch>='0'&&ch<='9';ch=getchar())x=x*10+ch-'0';
    x*=f;
}

typedef long long LL;
const int maxn=100010,mod=1000000007;
struct matrix{
    LL a[2][2];
    matrix(){memset(a,0,sizeof a);}
    matrix(LL x,LL y,LL p,LL q){
        a[0][0]=x;a[0][1]=y;
        a[1][0]=p;a[1][1]=q;
    }
    matrix operator*(const matrix b){
        matrix c;
        for(int i=0;i<=1;i++)
            for(int j=0;j<=1;j++)
                for(int k=0;k<=1;k++)
                    c.a[i][j]=(c.a[i][j]+a[i][k]*b.a[k][j]%mod)%mod;
        return c;
    }
    matrix operator+(const matrix b){
        matrix c;
        for(int i=0;i<=1;i++)
            for(int j=0;j<=1;j++)
                c.a[i][j]=(a[i][j]+b.a[i][j])%mod;
        return c;
    }
    matrix operator^(LL x){
        matrix c(1,0,0,1),a=*this;
        while(x){
            if(x&1)c=c*a;
            a=a*a;x>>=1;
        }
        return c;
    }
    bool operator==(const matrix b){
        return a[0][0]==b.a[0][0]&&a[0][1]==b.a[0][1]
                &&a[1][0]==b.a[1][0]&&a[1][1]==b.a[1][1];
    }
}orig(1,0,0,0),change(1,1,1,0),I(1,0,0,1);
struct Segment_Tree{
    #define lc x<<1
    #define rc x<<1|1
    int L[maxn<<2],R[maxn<<2];
    matrix tag[maxn<<2],sum[maxn<<2];
    void Build(int x,LL *a,int l,int r){
        L[x]=l;R[x]=r;tag[x]=I;
        if(l==r)return sum[x]=orig*(change^(a[l]-1)),void();
        int mid=(l+r)>>1;
        Build(lc,a,l,mid);Build(rc,a,mid+1,r);
        sum[x]=sum[lc]+sum[rc];
    }
    void pushdown(int x){
        if(tag[x]==I)return;
        tag[lc]=tag[lc]*tag[x];sum[lc]=sum[lc]*tag[x];
        tag[rc]=tag[rc]*tag[x];sum[rc]=sum[rc]*tag[x];
        tag[x]=I;
    }
    void Add(int x,int l,int r,matrix p){
        if(R[x]<l||L[x]>r)return;
        if(L[x]>=l&&R[x]<=r)return tag[x]=tag[x]*p,sum[x]=sum[x]*p,void();
        pushdown(x);
        Add(lc,l,r,p);Add(rc,l,r,p);
        sum[x]=sum[lc]+sum[rc];
    }
    LL Query(int x,int l,int r){
        if(R[x]<l||L[x]>r)return 0;
        if(L[x]>=l&&R[x]<=r)return sum[x].a[0][0];
        return pushdown(x),(Query(lc,l,r)+Query(rc,l,r))%mod;
    }
}tree;
int n,m;
LL a[maxn];

int main(){
    read(n);read(m);
    for(int i=1;i<=n;i++)read(a[i]);
    tree.Build(1,a,1,n);
    while(m--){
        int opt,l,r;LL x;
        read(opt);read(l);read(r);
        if(opt==1)read(x),tree.Add(1,l,r,change^x);
        else printf("%lld\n",tree.Query(1,l,r));
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章