【luogu P3128 [USACO15DEC]最大流Max Flow】 题解
题目链接:https://www.luogu.org/problemnew/show/P3128
菜
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define ll long long
#define lson left, mid, rt<<1
#define rson mid+1, right, rt<<1|1
using namespace std;
const ll maxn = 100000 + 10;
ll n, m, root;
ll fa[maxn], top[maxn], son[maxn], size[maxn], rev[maxn], seg[maxn], deep[maxn];
ll lazy[maxn<<2], tree[maxn<<2], res, num;
struct edge{
ll from, to, next;
}e[maxn<<2];
ll head[maxn], cnt;
void add(ll u, ll v)
{
e[++cnt].from = u;
e[cnt].to = v;
e[cnt].next = head[u];
head[u] = cnt;
}
//-----segment_tree-----
void PushUP(ll rt)
{
tree[rt] = max(tree[rt<<1], tree[rt<<1|1]);
}
void build(ll left, ll right, ll rt)
{
if(left == right)
{
tree[rt] = rev[left];
return;
}
ll mid = (left + right)>>1;
build(lson);
build(rson);
PushUP(rt);
}
void PushDOWN(ll left, ll right, ll rt, ll mid)
{
lazy[rt<<1] += lazy[rt];
lazy[rt<<1|1] += lazy[rt];
tree[rt<<1] += lazy[rt];//区间求和才需要加(mid - left + 1)*lazy[rt]
tree[rt<<1|1] += lazy[rt];//区间求最值只需要求一个值只需要加一次lazy[rt]
lazy[rt] = 0;
}
void update(ll l, ll r, ll add, ll left, ll right, ll rt)
{
if(l <= left && r >= right)
{
tree[rt] += add;
lazy[rt] += add;
return;
}
ll mid = (left + right)>>1;
if(lazy[rt]) PushDOWN(left, right, rt, mid);
if(l <= mid) update(l, r, add, lson);
if(r > mid) update(l, r, add, rson);
PushUP(rt);
}
ll query(ll l, ll r, ll left, ll right, ll rt)
{
ll res = -0x7fffffff;
if(l <= left && r >= right)
{
return tree[rt];
}
ll mid = (left + right)>>1;
if(lazy[rt]) PushDOWN(left, right, rt, mid);
if(l <= mid) res = max(query(l, r, lson), res);
if(r > mid) res = max(query(l, r, rson), res);
return res;
}
//----------------------
void dfs1(ll u, ll f, ll d)
{
ll maxson = -1;
size[u] = 1;
deep[u] = d;
fa[u] = f;
for(ll i = head[u]; i != -1; i = e[i].next)
{
ll v = e[i].to;
if(f != v)
{
dfs1(v, u, d+1);
size[u] += size[v];
if(maxson < size[v]) son[u] = v, maxson = size[v];
}
}
}
void dfs2(ll u, ll t)
{
seg[u] = ++num;
rev[num] = 0;
top[u] = t;
if(!son[u]) return;
dfs2(son[u], t);
for(ll i = head[u]; i != -1; i = e[i].next)
{
ll v = e[i].to;
if(v == fa[u] || v == son[u]) continue;
dfs2(v,v);
}
}
void updRange(ll x, ll y)
{
while(top[x] != top[y])
{
if(deep[top[x]] < deep[top[y]]) swap(x, y);
update(seg[top[x]], seg[x], 1, 1, n, 1);
x = fa[top[x]];
}
if(deep[x] > deep[y]) swap(x, y);
update(seg[x], seg[y], 1, 1, n, 1);
}
int main()
{
memset(head, -1, sizeof(head));
scanf("%lld%lld",&n,&m); root = 1;
for(ll i = 1; i < n; i++)
{
ll u, v;
scanf("%lld%lld",&u,&v);
add(u, v), add(v, u);
}
dfs1(root, 0, 1);
dfs2(root, root);
build(1, n, 1);
for(ll i = 1; i <= m; i++)
{
ll u, v;
scanf("%lld%lld",&u,&v);
updRange(u, v);
}
printf("%lld",tree[1]);
}
隐约雷鸣,阴霾天空,但盼风雨来,能留你在此。
隐约雷鸣,阴霾天空,即使天无雨,我亦留此地。