跳到正文

题解

Solution P6122

RuSun约 5 分钟
原文
文章信息与版本

文章信息

发布
2022年4月1日
收录
2026年7月8日
更新
2026年11月18日
篇幅
约 5 分钟
获赞
26
题目
P6122

版本

  1. v1当前

觉得两篇题解没有将流量的维护讲清楚,直接就胡过去了。

省选前发题解 RP++ 。

更好的阅读体验

先考虑费用流,树上双向边,容量无限,费用为 11 ,源点向所有有食物的点连边,所有鼹鼠向汇点连边。发现不能一次做完所有点,需要一个一个添加,费用流不方便做此题。

考虑模拟费用流,每新加入一个点,需要找到一条源点 →\to 加入的点 →\to 汇点的一条增广路,与源点汇点连接的边是唯一的,也就是需要在树上找到一条加入的点 →\to 有食物的点的最短路。现在考虑如何快速找到这样的最短路,注意到这是一棵二叉树,树高只有 log⁡n\log n ,考虑维护 fi,gif _ i, g _ i 表示点 ii 到其子树中有食物的点的最短路为多少、是哪个点。这样从一个点一直跳父亲,只需要 log⁡n\log n 次就可以确定这个点。确定点后需要将这一条路径的流量减一,反向边流量加一。

双向边以及它们的反向边的流量以及费用可以简单地用一个数组即可维护,原来的一对父子 p,sp, s 需要建边 (p,s,inf,1)(p, s, inf, 1) 以及反向边 (s,p,0,−1)(s, p, 0, -1) ;(s,p,inf,1)(s, p, inf, 1) 以及反向边 (p,s,0,−1)(p, s, 0, -1) ,无论是 p→sp \to s 还是 s→ps \to p ,都优先考虑走对方的反向边,因为反向边的费用为 −1-1 ,是更优的。这样的话,我们维护一个 wtiwt _ i 表示从 ii 的父亲到 ii 的正向边流量,当其为正的时候,表示存在边 (p,s,inf,1),(s,p,wti,−1)(p, s, inf, 1), (s, p, wt _ i, -1) ,父亲到儿子只能选择正向边,儿子到父亲优先选择父亲到儿子的反向边;当其为负的时候,表示存在边 (s,p,inf,1),(p,s,wti,−1)(s, p, inf, 1), (p, s, wt _ i, -1) ,儿子到父亲只能选择反向边,父亲到儿子优先选择反向边;当为 00 的时候,那么两者都没有流量,只能选择正向边。

新加入点 pp 时,先不断跳父亲,找到一个父亲 pospos 使得路径 p→pos→gposp \to pos \to g _ {pos} 是最短路,然后修改其中的流量,对于向上的边,相当于使 wt-- ,向下的边反之。修改完路径后,需要将所有 fi,gif _ i, g _ i 受到影响的点全部更新,即 p→pos,gpos→pos,pos→rootp \to pos, g _ {pos} \to pos, pos \to root 。

每个点完成后输出答案即可,复杂度 O(nlog⁡n)O(n \log n) 。

C++
#include <cstdio>
using namespace std;
template <class Type>
void read(Type &x)
{
    char c;
    bool flag = false;
    while ((c = getchar()) < '0' || c > '9')
        c == '-' && (flag = true);
    x = c - '0';
    while ((c = getchar()) >= '0' && c <= '9')
        x = (x << 3) + (x << 1) + c - '0';
    flag && (x = ~x + 1);
}
template <class Type>
void write(Type x)
{
    x < 0 && (putchar('-'), x = ~x + 1);
    x > 9 && (write(x / 10), 0);
    putchar(x % 10 + '0');
}
const int N = 1e5 + 10, inf = 2e6;
int n, m, c[N], f[N << 1], g[N << 1], wt[N];
void chkmin (int &x, int &mn, int t, int k)
{
    k < mn && (mn = k, x = t);
}
int cst_up (int x)
{
    return wt[x] > 0 ? -1 : 1;
}
int cst_down (int x)
{
    return wt[x] < 0 ? -1 : 1;
}
void update (int x)
{
    f[x] = inf;
    c[x] && (f[x] = 0, g[x] = x);
    x << 1 <= n && (chkmin(g[x], f[x], g[x << 1], f[x << 1] + cst_down(x << 1)), 0);
    (x << 1 | 1) <= n && (chkmin(g[x], f[x], g[x << 1 | 1], f[x << 1 | 1] + cst_down(x << 1 | 1)), 0);
}
int main ()
{
    read(n), read(m);
    for (int i = 1; i <= n; i++)
        read(c[i]);
    for (int i = n; i; i--)
        update(i);
    int res = 0;
    for (int p; m; m--)
    {
        read(p);
        int mn = inf, pos;
        for (int u = p, t = 0; u; t += cst_up(u), u >>= 1)
            chkmin(pos, mn, u, f[u] + t);
        res += mn;
        for (int u = p; u ^ pos; u >>= 1)
            wt[u]--, update(u);
        c[g[pos]]--;
        for (int u = g[pos]; u ^ pos; u >>= 1)
            wt[u]++, update(u);
        for (; pos; pos >>= 1)
            update(pos);
        write(res), putchar(' ');
    }
    return 0;
}
原文
存档评论2 条抓取于