华华开始学信息学(分块思想+树状数组)

题目链接

思路:

区间一个数的倍数的个数,我们可以 O(1)  算出的,问题在于要找的倍数有很多,考虑分块思想,把修改操作分为两类。

大于 sqrt(n) :

直接在树状数组中暴力 add

小于 sqrt(n) :

先记录下来,在每次查询操作时暴力计算

时间复杂度:

一次查询约是 O(sqrt(n))

Code:
 

#include <iostream>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
#include <vector>
#include <string>
#include <iomanip>
#include <cmath>
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <climits>
//#include <unordered_map>
#define guo312 std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
#define ll long long
#define Inf LONG_LONG_MAX
#define inf INT_MAX
#define endl "\n"
#define PI 3.1415926535898
using namespace std;
const int N=1e5+10;
int n,m,lk;
ll c[N];
int lowbit(int x){
	return x&(-x);
}
void add(int x,ll num){
	for( ;x<=n;c[x]+=num,x+=lowbit(x));
}
ll query(int x){
	ll re=0;
	for( ;x>0;re+=c[x],x-=lowbit(x));
	return re;
}
ll lazy[N];
int main(){
guo312;
	cin>>n>>m; lk=sqrt(n);
	ll op,l,r,d,k;
	for(int i=1;i<=m;i++){
		cin>>op;
		if(op==1){
			cin>>d>>k;
			if(d<lk){
				lazy[d]+=k;
			}
			else{
				for(int j=d;j<=n;j+=d){
					add(j,k);
				}
			}
		}
		else{
			cin>>l>>r;
			ll ans=query(r)-query(l-1);
			for(int i=1;i<lk;i++){
				ans+=(r/i-(l-1)/i)*lazy[i];
			}
			cout<<ans<<endl;
		}
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

要用bug来打败bug

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值