Codeforces 1062C. Banh-mi

找规律题,设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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值