找规律题,设l-r区间中1出现次数为c1,0出现的次数为c2,答案就是(2^c1-1)* 2 ^c2
一开始想的快速幂,然而还是TLE,就只能打表了。
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
char c;
int a[101001],n,p,l,r;
const LL mod = 1e9+7;
LL num[101010];
int main(){
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin>>n>>p;
num[0] = 1;
for(int i =1;i<100001;i++)
num[i] = num[i-1]*2 %mod;
for(int i = 1;i<=n;i++) {
cin>>c;
a[i] = a[i-1] + c - '0';
}
while(p--){
cin>>l>>r;
cout<<(LL)(num[a[r]-a[l-1]]-1)*(LL)num[r-l+1-a[r]+a[l-1]]%mod<<endl;
}
return 0;
}
附上快速幂的代码。
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL mod = 1e9+7;
LL f1(LL x,LL n,LL mod){
LL ans = 0;
while(n){
if(n&1) ans += x;
x = (x+x)%mod;
ans %= mod ;
n/=2;
}
return ans;
}
LL f2(LL x,LL n,LL mod){
LL ans = 1;
while(n){
if(n&1) ans =f1(ans,x,mod);
x = f1(x,x,mod);
x %= mod;
ans %=mod;
n/=2;
}
return ans;
}
int n,q,b[101010],l,r;LL num1,num0;
char a[101010];
int main(){
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin>>n>>q;
for(int i = 1;i<=n;i++) cin>>a[i],b[i] = b[i-1] + a[i] - '0';
while(q--){
cin>>l>>r;
num1 = b[r] - b[l-1] ;
num0 = r - l + 1 - num1;
cout<<(((f2(2,num1,mod)-1)%mod )* (f2(2,num0,mod)%mod))%mod<<endl;
}
return 0;