C. Banh-mi

链接

[http://codeforces.com/contest/1062/problem/C]

题意

给你有n个字符(0 or 1)的串,当去某个位置时所有的剩下的位置都加上这个位置的数字,q次查询l,r区间
进行操作完,最后和是多少,对1e9+7取模?

分析

其实某个区间与01的位置没关系只与01 个数有关,如果有x个1,y个0,直接用sum前缀和统计
那么结果就是
ans=pow(2ll,sum[r]-sum[l-1],inf)-1;
ans=(ans+(ans*(pow(2ll,r-l+1+sum[l-1]-sum[r],inf)-1))%inf)%inf;
pow是快速幂
详解链接
[https://www.cnblogs.com/mch5201314/p/9523473.html]

代码

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const ll inf=1e9+7;
ll sum[1000005];
ll pow(ll a,ll b,ll n){
    ll ans=1;
    ll base=a;
    while(b){
        if(b&1) ans=ans*base%n;
        base=base*base%n;
        b>>=1;
    }
    return ans;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    ll n,q;
    char s[1000005];
    //freopen("in.txt","r",stdin);
    while(cin>>n>>q){
        cin>>s+1;
        memset(sum,0,sizeof(sum));
       for(int i=1;i<=n;i++)
        if(s[i]=='1') sum[i]=sum[i-1]+1;
        else sum[i]=sum[i-1];
        int l,r;
        while(q--){
            ll ans=0;
            cin>>l>>r;
            ans=pow(2ll,sum[r]-sum[l-1],inf)-1;
            ans=(ans+(ans*(pow(2ll,r-l+1+sum[l-1]-sum[r],inf)-1))%inf)%inf;
            cout<<ans<<endl;
           }
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/mch5201314/p/9970927.html