北大集训 2021 小明的树 题解报告
Cocoly1990 · · 题解
考虑对边分类,记两个端点都未点亮的边为黑边,一个端点点亮一个端点为点亮的边为黑白边,两个端点都点亮的边为白边。
然后,美丽的定义等价于所有的黑边构成连通块。
考察一个经典结论:连通块个数等于点数减边数。
记当前操作次数为
这时候对计数器的贡献是黑白边的个数。
然后,考虑线段树维护这个东西,对时间轴建立线段树。
考察一条边
-
一开始,对黑边贡献为
1 。 -
然后,遇到
t_x 时,黑边减一,黑白边加一。 -
遇到
t_y 时,黑白边减一,白边加一。
然后,把黑白边的个数看作权值,把
修改操作的话,沿用上面的思路,对贡献操作就好了。相当于一个区间加的操作。
#include<bits/stdc++.h>
#define Maxn 500007
using namespace std;
int n, q, p[Maxn], a[Maxn], U[Maxn], V[Maxn];
struct Seg{
int ls(int x) {return x << 1;} int rs(int x) {return x << 1 | 1;}
int cnt[Maxn << 2], mn[Maxn << 2], tag[Maxn << 2][2]; long long sum[Maxn << 2]; //0 min 1 bw
void pushup(int p){
mn[p] = min(mn[ls(p)], mn[rs(p)]); cnt[p] = sum[p] = 0;
if(mn[p] == mn[ls(p)]) cnt[p] += cnt[ls(p)], sum[p] += sum[ls(p)];
if(mn[p] == mn[rs(p)]) cnt[p] += cnt[rs(p)], sum[p] += sum[rs(p)];
}
void pushdown(int p){
if(tag[p][0]) {tag[ls(p)][0] += tag[p][0]; tag[rs(p)][0] += tag[p][0]; mn[ls(p)] += tag[p][0]; mn[rs(p)] += tag[p][0]; tag[p][0] = 0;}
if(tag[p][1]) {tag[ls(p)][1] += tag[p][1]; tag[rs(p)][1] += tag[p][1]; sum[ls(p)] += 1ll * tag[p][1] * cnt[ls(p)]; sum[rs(p)] += 1ll * tag[p][1] * cnt[rs(p)]; tag[p][1] = 0;}
}
void build(int p, int l, int r){
cnt[p] = mn[p] = sum[p] = tag[p][0] = tag[p][1] = 0;
if(l == r) {cnt[p] = 1; mn[p] = n - l + (n == l); return;}
int mid = (l + r) >> 1; build(ls(p), l, mid); build(rs(p), mid + 1, r); pushup(p);
}
void motify(int p, int l, int r, int ql, int qr, int x, int y){
if(ql <= l and r <= qr) {tag[p][0] += x; tag[p][1] += y; mn[p] += x; sum[p] += 1ll * cnt[p] * y; return;}
pushdown(p); int mid = (l + r) >> 1;
if(ql <= mid) motify(ls(p), l, mid, ql, qr, x, y);
if(qr > mid) motify(rs(p), mid + 1, r, ql, qr, x, y); pushup(p);
}
void add(int x, int y, int k){
x = p[x], y = p[y]; if(x > y) swap(x, y);
if(x >= 2) motify(1, 1, n, 1, x - 1, - k, 0);
if(y > x) motify(1, 1, n, x, y - 1, 0, k);
}
}t;
int main(){
ios :: sync_with_stdio(false); cin.tie(0); cout.tie(0);
cin >> n >> q;
for(int i = 1; i < n; i ++) cin >> U[i] >> V[i];
for(int i = 1; i < n; i ++) cin >> a[i], p[a[i]] = i; p[a[n] = 1] = n;
t.build(1, 1, n);
for(int i = 1; i < n; i ++) t.add(U[i], V[i], 1); cout << t.sum[1] << "\n";
for(int u, v, l, w; q; q --){
cin >> u >> v >> l >> w;
t.add(u, v, -1); t.add(l, w, 1);
cout << t.sum[1] << "\n";
}
}
后记:很厉害的题,当年模拟赛出了这题,全网没有题解,我们一车人对着墨染空的做题记录看了 114514 年。