USACO 2015 December Contest, Platinum Problem Max Flow【树链剖分】

时间:2023-03-08 17:41:01

  题意比较难理解,就是给你n个点的树,然后给你m个修改操作,每一次修改包括一个点对(x, y),意味着将x到y所有的点权值加一,最后问你整个树上的点权最大是多少。

  

  比较裸的树链剖分了,感谢Haild的讲解。

  首先第一遍dfs预处理出size,son(重儿子)。

  第二遍dfs重编号。

  然后线段树就可以了。

  感觉就是把一棵树弄成一条一条的链,新奇的hash方法。

 #include <bits/stdc++.h>
#define rep(i, a, b) for (int i = a; i <= b; i++)
#define drep(i, a, b) for (int i = a; i >= b; i--)
#define REP(i, a, b) for (int i = a; i < b; i++)
#define pb push_back
#define mp make_pair
#define clr(x) memset(x, 0, sizeof(x))
#define xx first
#define yy second
using namespace std;
typedef long long i64;
typedef pair<int, int> pii;
const int inf = ~0U >> ;
const i64 INF = ~0ULL >> ;
//******************************* template <typename T> void MAX(T &a, T &b) { if (a < b) a = b; }
template <typename T> void MIN(T &a, T &b) { if (a > b) a = b; } const int maxn = ; struct Ed {
int u, v, nx; Ed() {}
Ed(int _u, int _v, int _nx) :
u(_u), v(_v), nx(_nx) {}
} E[maxn << ];
int G[maxn], edtot;
void addedge(int u, int v) {
E[++edtot] = Ed(u, v, G[u]);
G[u] = edtot;
E[++edtot] = Ed(v, u, G[v]);
G[v] = edtot;
} struct Seg_Tree {
int lazy[maxn << ], Max[maxn << ];
void Push_down(int o) {
if (!lazy[o]) return;
lazy[o << ] += lazy[o], lazy[o << | ] += lazy[o];
Max[o << ] += lazy[o], Max[o << | ] += lazy[o];
lazy[o] = ;
}
void Push_up(int o) { Max[o] = max(Max[o << ], Max[o << | ]); }
void update(int o, int l, int r, int ql, int qr, int v) {
if (ql <= l && r <= qr) {
lazy[o] += v;
Max[o] += v;
return;
}
Push_down(o);
int mid = l + r >> ;
if (ql <= mid) update(o << , l, mid, ql, qr, v);
if (qr > mid) update(o << | , mid + , r, ql, qr, v);
Push_up(o);
}
} T; int size[maxn], pre[maxn], son[maxn], dep[maxn];
int dfs_size(int x, int fa) {
size[x] = ; int haha = -inf; pre[x] = fa; dep[x] = dep[fa] + ;
for (int i = G[x]; i; i = E[i].nx) if (E[i].v != fa) {
size[x] += dfs_size(E[i].v, x);
if (size[E[i].v] > haha) haha = size[E[i].v], son[x] = E[i].v;
}
return size[x];
}
int ndtot, pos[maxn], top[maxn];
void repos(int x, int tp) {
pos[x] = ++ndtot;
top[x] = tp;
if (son[x]) repos(son[x], tp);
for (int i = G[x]; i; i = E[i].nx) if (E[i].v != pre[x] && E[i].v != son[x]) repos(E[i].v, E[i].v);
} int n;
void update(int x, int y) {
while (top[x] != top[y]) {
if (dep[top[x]] < dep[top[y]]) swap(x, y);
T.update(, , n, pos[top[x]], pos[x], ); x = pre[top[x]];
}
T.update(, , n, min(pos[x], pos[y]), max(pos[x], pos[y]), );
} int main() {
freopen("maxflow.in", "r", stdin);
freopen("maxflow.out", "w", stdout);
int m; scanf("%d%d", &n, &m);
REP(i, , n) {
int x, y; scanf("%d%d", &x, &y);
addedge(x, y);
}
dfs_size(, );
repos(, );
while (m--) {
int x, y; scanf("%d%d", &x, &y);
update(x, y);
}
printf("%d\n", T.Max[]);
return ;
}