P2146 [NOI2015] 软件包管理器
思路分析
树链剖分板子,每次安装时,将 \(1\) 到 \(x\) 的链变为 \(1\),卸载时,将 \(x\) 的子树变为 \(0\)。
代码
#include<iostream>
using namespace std;
inline int read(){register int x = 0, f = 1;register char c = getchar();while (c < '0' || c > '9'){if (c == '-') f = -1;c = getchar();}while (c >= '0' && c <= '9'){x = (x << 1) + (x << 3) + (c ^ 48);c = getchar();}return x * f;}
inline void write(int x){if (x < 0) putchar('-'), x = -x;if (x > 9) write(x / 10);putchar(x % 10 + '0');}
const int N = 1e5 + 10;
int n, q;
struct edge{
int v, nxt;
}e[N << 1];
int head[N], cnt;
int sz[N], dep[N], son[N], f[N], id[N], top[N], tot;
void add(int u, int v){
e[++cnt] = (edge){v, head[u]};
head[u] = cnt;
}
void dfs1(int u, int fa){
sz[u] = 1, f[u] = fa, dep[u] = dep[fa] + 1;
for (int i = head[u]; i; i = e[i].nxt){
int v = e[i].v;
if (v == fa) continue;
dfs1(v, u);
sz[u] += sz[v];
if (sz[v] > sz[son[u]]) son[u] = v;
}
}
void dfs2(int u, int t){
id[u] = ++tot;
top[u] = t;
if (son[u]) dfs2(son[u], t);
for (int i = head[u]; i; i = e[i].nxt){
int v = e[i].v;
if (v == f[u] || v == son[u]) continue;
dfs2(v, v);
}
}
struct tree{
int sum, tag;
}t[N << 2];
void pushup(int now){
t[now].sum = t[now << 1].sum + t[now << 1 | 1].sum;
}
void pushdown(int now, int l, int r){
if (t[now].tag != -1){
int mid = (l + r) >> 1;
t[now << 1].sum = t[now].tag * (mid - l + 1);
t[now << 1 | 1].sum = t[now].tag * (r - mid);
t[now << 1].tag = t[now].tag;
t[now << 1 | 1].tag = t[now].tag;
t[now].tag = -1;
}
}
void build(int now, int l, int r){
t[now].tag = -1, t[now].sum = 0;
if (l == r) return;
int mid = (l + r) >> 1;
build(now << 1, l, mid);
build(now << 1 | 1, mid + 1, r);
}
void modify(int now, int l, int r, int x, int y, int k){
if (x <= l && r <= y){
t[now].sum = k * (r - l + 1), t[now].tag = k;
return;
}
pushdown(now, l, r);
int mid = (l + r) >> 1;
if (x <= mid) modify(now << 1, l, mid, x, y, k);
if (mid + 1 <= y) modify(now << 1 | 1, mid + 1, r, x, y, k);
pushup(now);
}
void modify_chain(int x, int y, int k){
int fx = top[x], fy = top[y];
while (fx != fy){
if (dep[fx] < dep[fy]) swap(x, y), swap(fx, fy);
modify(1, 1, n, id[fx], id[x], k);
x = f[fx], fx = top[x];
}
if (id[x] > id[y]) swap(x, y);
modify(1, 1, n, id[x], id[y], k);
}
int main(){
n = read();
for (int i = 1; i < n; i++){
int x = read() + 1;
add(x, i + 1);
}
dfs1(1, 0);
dfs2(1, 1);
build(1, 1, n);
q = read();
for (int i = 1; i <= q; i++){
char c[10];
cin >> c;
int OP = t[1].sum, x = read() + 1;
if (c[0] == 'i'){
modify_chain(1, x, 1);
cout << t[1].sum - OP << '\n';
}else{
modify(1, 1, n, id[x], id[x] + sz[x] - 1, 0);
cout << OP - t[1].sum << '\n';
}
}
return 0;
}
标签:总结,10,dfs2,int,son,2024,read,寒假,id
From: https://www.cnblogs.com/bryceyyds/p/18017930