Codeforce1062C(数学+快速幂)

#Banh-mi
传送门
####思路:有题意可知在区间内取数的位置不影响结果,且要使得答案最大我们要从1开始取。
1   1   1   0   0   0
1]  2   2   1   1   1
     2]  4   3   3   3
          4]  7   7   7
               7]  14 14
                   14]  28
                         28]
1+2+4+7+14+28=56

   20 + 21 + 22 + 23 - 20 + 24 - 21 + 25-22
= 23 + 24+ 25
=(20 + 21 + 22)*23
=(23-1)*23
如果用a代表1的数量,b代表0的数量
则有ans=(2a-1) * 2b

所以预处理字符串前缀1和0的数量,每一次询问便可得到区间1和0的数量,然后通过快速幂取模得到ans

#include <bits/stdc++.h>
#define inf 1000000007
using namespace std;
typedef long long ll;
const int MAXN=2e5+10;
const int MAX=1e5+10;
const ll BIG=1e11+10;
const double eps=1e-6;
const double PI=3.14159;
const ll mod=1000000007;

int n,q;
string s;
int one[MAX],zero[MAX];

ll mypow(ll a,ll n,ll MOD){
    ll res=1;
    while(n){
        if(n%2==1){
            res*=a;
            res=res%MOD;
            n--;
        }
        n=n/2;
        a=(a*a)%MOD;
    }
    return res;
}

int main(){
    #ifdef ONLINE_JUDGE
    #else
    freopen("in.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    #endif

    while(cin>>n>>q){
        cin>>s;
        int len=s.size();
        memset(one,0,sizeof(one));
        memset(zero,0,sizeof(zero));
        for(int i=0;i<len;i++){
            one[i+1]=one[i];
            zero[i+1]=zero[i];
            if(s[i]=='0')   zero[i+1]++;
            else    one[i+1]++;;
        }
        int l,r;
        ll a,b;
        while(q--){
            scanf("%d%d",&l,&r);
            a=one[r];
            b=zero[r];
            a-=one[l-1];
            b-=zero[l-1];
            ll ans=mypow(2,a,mod)-1;
            ans=(ans*mypow(2,b,mod))%mod;

            cout<<ans<<endl;
        }
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值