Adding Edges

· · 题解

Adding Edges

题意

题解

考虑压缩 G,如果存在 (a,b),(a,c) 且在 T 中存在一条路径顺次包含 a,b,c,那么删除 (a,c) 加上 (b,c) 不改变答案。

对 G 进行充分压缩后,有结论:最终 (x,y) 有边当且仅当存在 a_1,a_2,\cdots,a_t 满足:

这个就很好统计了,考虑如何压缩 G。

对于一条加边 (a,b),记 p(a,b) 表示在 T 中以 a 为根离 b 最近且在 G 中与 b 相连的祖先,若 p(a,b) 存在,则应该直接加 (b,p(a,b)),否则将 b 子树打上标记,碰到边时压缩即可。

时间复杂度 \mathcal O(n(n+m))。

代码

const int N = 2e3 + 7;
int n, m, ans;
vi e[N];
int f[N][N], p[N][N];
bool g[N][N];

void dfs(int x, int *f) {
    for (int y : e[x])
        if (y != f[x]) f[y] = x, dfs(y, f);
}

inline void add(int x, int y) {
    if (p[x][y] == y || p[y][x] == x) return;
    if (p[x][y]) return add(p[x][y], y);
    if (p[y][x]) return add(p[y][x], x);
    vector<pi> a;
    for (int i = 0; i < 2; i++) {
        g[x][y] = 1, p[x][y] = y;
        queue<int> q;
        q.push(y);
        while (q.size()) {
            int u = q.front();
            q.pop();
            for (int v : e[u])
                if (v != f[x][u]) {
                    if (!p[x][v]) p[x][v] = y, q.push(v);
                    else if (g[x][v]) g[x][v] = g[v][x] = 0, a.pb(mp(y, v));
                }
        }
        swap(x, y);
    }
    for (pi o : a) add(o.fi, o.se);
}

void dfs1(int x, int t, int *f) {
    if (p[t][x] == x) ++ans, t = x;
    for (int y : e[x])
        if (y != f[x]) dfs1(y, t, f);
}

int main() {
    rd(n, m);
    for (int i = 1, x, y; i < n; i++) rd(x, y), e[x].pb(y), e[y].pb(x);
    for (int x = 1; x <= n; x++) dfs(x, f[x]);
    for (int i = 1, x, y; i <= m; i++) rd(x, y), add(x, y);
    for (int x = 1; x <= n; x++)
        for (int y : e[x]) dfs1(y, x, f[x]);
    print(ans >> 1);
    return 0;
}