BZOJ3922 Karin的弹幕 【线段树】
题目链接
题解
考虑暴力,修改\(O(1)\),查询\(O(\frac{n}{d})\)
考虑线段树,如果对每种差值建一棵线段树,修改\(O(nlogn)\),查询\(O(logn)\)
能不能均摊?
线段树查询快,修改慢
暴力修改快,查询慢
容易发现当\(d\)比较大时暴力还是可以接受的,所以我们不需要建那么多线段树
我们设我们对前\(T\)种差值建线段树
那么暴力查询总共\(O(m\frac{n}{T})\),线段树修改总共\(O(mTlogn)\)
我们令
\[m\frac{n}{T} = mTlogn
\]
解得
\[T = \sqrt{\frac{n}{logn}}
\]
总复杂度\(O(n\sqrt{nlogn})\)
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<map>
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define mp(a,b) make_pair<int,int>(a,b)
#define cls(s) memset(s,0,sizeof(s))
#define cp pair<int,int>
#define LL long long int
#define ls (u << 1)
#define rs (u << 1 | 1)
using namespace std;
const int maxn = 70005,maxm = 100005,INF = 1000000000;
inline int read(){
int out = 0,flag = 1; char c = getchar();
while (c < 48 || c > 57){if (c == '-') flag = -1; c = getchar();}
while (c >= 48 && c <= 57){out = (out << 3) + (out << 1) + c - 48; c = getchar();}
return out * flag;
}
int B,n,m,id[70][maxn],A[maxn],C[maxn];
struct Segmnet_Tree{
int mx[maxn << 2];
void upd(int u){mx[u] = max(mx[ls],mx[rs]);}
void build(int u,int l,int r){
if (l == r) {mx[u] = C[l]; return;}
int mid = l + r >> 1;
build(ls,l,mid);
build(rs,mid + 1,r);
upd(u);
}
void modify(int u,int l,int r,int pos,int v){
if (l == r){mx[u] += v; return;}
int mid = l + r >> 1;
if (mid >= pos) modify(ls,l,mid,pos,v);
else modify(rs,mid + 1,r,pos,v);
upd(u);
}
int query(int u,int l,int r,int L,int R){
if (l >= L && r <= R) return mx[u];
int mid = l + r >> 1;
if (mid >= R) return query(ls,l,mid,L,R);
if (mid < L) return query(rs,mid + 1,r,L,R);
return max(query(ls,l,mid,L,R),query(rs,mid + 1,r,L,R));
}
}T[70];
int main(){
n = read(); B = (int)sqrt(n / (log(n) / (log(2))));
REP(i,n) A[i] = read();
for (int t = 1; t <= B; t++){
int cnt = 0;
for (int i = 1; i <= t; i++){
for (int j = i; j <= n; j += t){
id[t][j] = ++cnt;
C[cnt] = A[j];
}
}
T[t].build(1,1,n);
}
m = read();
int opt,v,x,d,l,r;
while (m--){
opt = read();
if (!opt){
x = read(); v = read(); A[x] += v;
for (int t = 1; t <= B; t++)
T[t].modify(1,1,n,id[t][x],v);
}
else {
x = read(); d = read();
if (d <= B){
l = id[d][x]; r = id[d][x + (n - x) / d * d];
printf("%d\n",T[d].query(1,1,n,l,r));
}
else {
v = A[x];
for (int i = x + d; i <= n; i += d)
v = max(v,A[i]);
printf("%d\n",v);
}
}
}
return 0;
}