左偏树
是一种稳定O(logN)的可并堆算法。
为了做到这个复杂度,我们要保证这么两个事情。以小根堆为例。
1、
lson(x)
l
s
o
n
(
x
)
与
rson(x)
r
s
o
n
(
x
)
均小于等于
x
x
。(
like
l
i
k
e
heap
h
e
a
p
)
2、我们定义一个点的
dist(x)=dist(rson(x))+1
d
i
s
t
(
x
)
=
d
i
s
t
(
r
s
o
n
(
x
)
)
+
1
。那么性质就是:
必有dist(lson(x))≥dist(rson(x))
必
有
d
i
s
t
(
l
s
o
n
(
x
)
)
≥
d
i
s
t
(
r
s
o
n
(
x
)
)
。(不满足的话我们可以
swap
s
w
a
p
,这倒不是问题)
于是可以得到推论:根的最大距离为
logN
l
o
g
N
级。也就是说我们沿着右边遍历,最多
logN
l
o
g
N
次。于是我们就递归合并咯。
然后有了合并操作,我们就可以支持各种各样的操作了。(再次安利
fhq
f
h
q
treap
t
r
e
a
p
)
城池攻占
树上可并堆。dfs去做,要标记一个乘法一个加法标记。这种乘法加法标记的题最需要注意运算法则顺序了!千万不要写错哦!
题目保证不超过
longlong
l
o
n
g
l
o
n
g
,不用取模,还算良心~
常数大的不提了。
#include <cstdio>
#include <algorithm>
#include <vector>
#define N 300010
typedef long long ll;
using namespace std;
inline char gc() {
static char now[1<<16], *S, *T;
if(S == T) {T = (S = now) + fread(now, 1, 1<<16, stdin); if(S == T) return EOF;}
return *S++;
}
inline ll read() {
ll x = 0, f = 1; char c = gc();
while(c < '0' || c > '9') {if(c == '-') f = -1; c = gc();}
while(c >= '0' && c <= '9') {x = x * 10 + c - 48; c = gc();}
return x * f;
}
vector<int> son[N];
bool a[N];
int c[N], rt[N], lc[N], rc[N], dis[N], dep[N], dead[N], num[N];
ll h[N], v[N], mul[N], add[N], val[N];
int n, m;
inline void cov(int x, ll cf, ll jf) {
if(!x) return ;
v[x]*= cf; v[x]+= jf;
mul[x]*= cf; add[x]*= cf; add[x]+= jf;
}
inline void pushdown(int x) {
cov(lc[x], mul[x], add[x]);
cov(rc[x], mul[x], add[x]);
mul[x] = 1; add[x] = 0;
}
int merge1(int x, int y) {
if(!x || !y) return x + y;
pushdown(x); pushdown(y);
if(v[x] > v[y]) swap(x, y);
rc[x] = merge1(rc[x], y);
if(dis[lc[x]] < dis[rc[x]]) swap(lc[x], rc[x]);
dis[x] = dis[rc[x]] + 1;
return x;
}
void dfs(int x) {
for(int i = 0; i < son[x].size(); ++i) {
int y = son[x][i]; dep[y] = dep[x] + 1;
dfs(y); rt[x] = merge1(rt[x], rt[y]);
}
while(rt[x] && v[rt[x]] < h[x]) {
pushdown(rt[x]);
++dead[x]; num[rt[x]] = dep[c[rt[x]]] - dep[x];
rt[x] = merge1(lc[rt[x]], rc[rt[x]]);
}
if(a[x]) cov(rt[x], val[x], 0);
else cov(rt[x], 1, val[x]);
}
int main() {
n = read(); m = read();
for(int i = 1; i <= n; ++i) h[i] = read();
for(int i = 2; i <= n; ++i) {
int fa = read(); a[i] = (bool)read(); val[i] = read();
son[fa].push_back(i);
}
for(int i = 1; i <= m; ++i) {
v[i] = read(); c[i] = read();
if(v[i] >= h[c[i]]) {
mul[i] = 1;
rt[c[i]] = merge1(rt[c[i]], i);
}else ++dead[c[i]], num[i] = 0;
}
dfs(1);
while(rt[1]) {
pushdown(rt[1]);
num[rt[1]] = dep[c[rt[1]]] + 1;
rt[1] = merge1(lc[rt[1]], rc[rt[1]]);
}
for(int i = 1; i <= n; ++i) printf("%d\n", dead[i]);
for(int i = 1; i <= m; ++i) printf("%d\n", num[i]);
return 0;
}