根号分治本质是一种暴力,主要应用在这种题目中:
- 修改/询问值小的时候暴力很慢,但预处理后修改/查询很方便;值大时暴力又很优秀,但不好预处理。
针对这种情况,我们可以设立一个阈值,将操作值大于/小于两种情况分开处理,一般阈值达到根号的时候复杂度最优,达到单次 。
这样讲还是很抽象,先看题。
例题 1:哈希冲突
本质就是支持两种操作:
-
修改操作:将第 个数修改为 。
-
查询操作:询问
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 15e4 + 9,SqrtN = 409;
int n,m,sqrt_n;
int a[N];
int sum[SqrtN][SqrtN];//ans[i][j]:模i为j的下标对应的数的和
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin >> n >> m;
sqrt_n = sqrt(n);
for(int i = 1;i <= n;i++)
cin >> a[i];
for(int i = 1;i <= n;i++)
for(int j = 1;j <= sqrt_n;j++)
sum[j][i % j] += a[i];
while(m--){
string op;
int x,y;
cin >> op >> x >> y;
if(op == "A"){
int ans = 0;
if(x > sqrt_n){
for(int i = y;i <= n;i += x)
ans += a[i];
cout << ans << '\n';
}
else
cout << sum[x][y] << '\n';
}
else{
for(int i = 1;i <= sqrt_n;i++)
sum[i][x % i] += y - a[x];
a[x] = y;
}
}
return 0;
}