1. 程式人生 > >Subsequence Count 2017ccpc網路賽 1006 dp+線段樹維護矩陣

Subsequence Count 2017ccpc網路賽 1006 dp+線段樹維護矩陣

#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i=a;i<=b;++i)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
int N,Q;
const long long int mo=1e9+7;
char s[5010];
int lazy[5050<<2];
struct Matrix{
    int n,m;
    long long a[3][3];
    Matrix (){clear();}
    
void clear(){ n=m=3; memset(a,0,sizeof(a)); } Matrix operator *(const Matrix &b) const{ Matrix tmp; for (int i=0;i<n;++i) for (int j=0;j<b.m;++j) for (int k=0;k<m;++k) tmp.a[i][j]=(tmp.a[i][j]+a[i][k]*b.a[k][j])%mo;
return tmp; } }; Matrix A0,A1,E; Matrix cnt[5050<<2]; inline void init() { A0.a[0][0]=1,A0.a[0][1]=0,A0.a[0][2]=0; A0.a[1][0]=1,A0.a[1][1]=1,A0.a[1][2]=0; A0.a[2][0]=1,A0.a[2][1]=0,A0.a[2][2]=1; A1.a[0][0]=1,A1.a[0][1]=1,A1.a[0][2]=0; A1.a[1][0]=0,A1.a[1][1]=1,A1.a[1][2]=0; A1.a[2][0]=0,A1.a[2][1
]=1,A1.a[2][2]=1; E.a[0][0]=1,E.a[0][1]=0,E.a[0][2]=0; E.a[1][0]=0,E.a[1][1]=1,E.a[1][2]=0; E.a[2][0]=0,E.a[2][1]=0,E.a[2][2]=1; } inline void Pushup(int rt) { cnt[rt]=cnt[rt<<1]*cnt[rt<<1|1]; } inline void build(int l,int r,int rt) { if(l==r) { if(s[l-1]-'0'==0) { cnt[rt]=A0; } else cnt[rt]=A1; return; } int m=(l+r)>>1; build(lson); build(rson); Pushup(rt); } inline void change(Matrix &X) { swap(X.a[0][0],X.a[1][1]); swap(X.a[0][1],X.a[1][0]); swap(X.a[2][0],X.a[2][1]); } inline void pushdown(int rt) { if(lazy[rt]) { change(cnt[rt<<1]); change(cnt[rt<<1|1]); lazy[rt<<1]^=1; lazy[rt<<1|1]^=1; lazy[rt]=0; } } inline void update(int a,int b,int l,int r,int rt) { if(l>=a&&r<=b) { change(cnt[rt]); lazy[rt]^=1; return; } pushdown(rt); int m=(l+r)>>1; if(a<=m) update(a,b,lson); if(b>m) update(a,b,rson); Pushup(rt); } inline void Input() { scanf("%d%d",&N,&Q); scanf("%s",s); } inline Matrix query(int a,int b,int l,int r,int rt) { if(l>=a&&r<=b) return cnt[rt]; pushdown(rt); Matrix t1=E,t2=E; int m=(r+l)>>1; if(a<=m) t1=query(a,b,lson); if(b>m) t2=query(a,b,rson); return t1*t2; } int main() { //freopen("in.txt","r",stdin); int T,type,l,r; scanf("%d",&T); init(); rep(t,1,T) { Input(); build(1,N,1); rep(i,1,Q) { scanf("%d%d%d",&type,&l,&r); if(type==1) { update(l,r,1,N,1); // rep(j,1,2*N) printf("i=%d dp%d=%lld\n",i,j,(cnt[j].a[2][0]+cnt[j].a[2][1])%mo); } else { Matrix tmp; tmp=query(l,r,1,N,1); printf("%lld\n",(tmp.a[2][0]+tmp.a[2][1])%mo); } } } return 0; }