---
id: 2378
lang: en
translation_of: index.md
source_sha256: eedb943e1fb74f12e5a727db590229cddb3c8352816f99311a46e6b7330750a3
title: "P5327: [ZJOI2019] Language — Solution"
description: "The countries each node can trade with form a connected subgraph; maintain these node sets with tree differences and segment tree merging, sized via LCA depths."
tags: ["OI","Segment Tree Merging","Difference on Trees","LCA"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "异象石 is the name of a classic problem (linked); rendered literally as Anomaly Stones and chipped, reusing the gloss from post 1721. The first occurrence is link text and is left unchipped: a chip inside a link navigates away on tap instead of showing its tooltip (render-check fails on mobile); the second occurrence carries the chip."
  - "交集 is translated literally as “intersection”, as written."
---

## Main Idea

Great problem! Great problem!

First, this problem requires knowing one property: the set of countries that each point can reach and trade with forms a connected spanning subgraph. So what we ultimately need to compute is the size of the set corresponding to each country.

How do we compute this quickly? We need to take out every one of the $m$ paths that passes over the current point $u$, and then compute the intersection of these paths. This is one way to compute it, but it really isn't fast.

<!--more-->

Let's try to optimize this method to get the intended solution. Consider a static problem: given a point set $S$, compute the size of its spanning tree. This is actually “[Anomaly Stones](https://loj.ac/problem/10132)”: we need the pairwise LCAs and then use the depth information to compute the size. The problem is that we can't do that here, or it would still time out.

If only we could use difference on trees to batch-modify the point set. Here we can actually use segment tree merging to maintain this information: each leaf of a segment tree represents a difference point, we can use the $DFS$ order as the index, and then when merging two intervals that are consecutive in DFS order, we can directly use the method from <span class="slang" data-zh="异象石" data-gloss="yìxiàng shí, “anomaly stones”. A classic tree problem: keep the total length of the paths joining a changing set of marked nodes, using sums of pairwise distances.">Anomaly Stones</span>.

## Code

```cpp
// P5327.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 2e5 + 200;

typedef long long ll;

int n, head[MAX_N], current, dfn[MAX_N], st[20][MAX_N], stot, ptot;
int log2_[MAX_N], dep[MAX_N], m, roots[MAX_N], up[MAX_N];
vector<int> remTag[MAX_N];
ll ans;

struct edge
{
    int to, nxt;
} edges[MAX_N << 1];

struct node
{
    int val, lson, rson, s, t, sum;
} nodes[MAX_N * 30];

void addpath(int src, int dst)
{
    edges[current].to = dst, edges[current].nxt = head[src];
    head[src] = current++;
}

void dfs(int u, int fa)
{
    up[u] = fa, st[0][++stot] = u, dfn[u] = stot, dep[u] = dep[fa] + 1;
    for (int i = head[u]; i != -1; i = edges[i].nxt)
        if (edges[i].to != fa)
            dfs(edges[i].to, u), st[0][++stot] = u;
}

int gmin(int x, int y) { return dep[x] < dep[y] ? x : y; }

int getLCA(int x, int y)
{
    if (x == 0 || y == 0)
        return 0;
    if (dfn[x] > dfn[y])
        swap(x, y);
    int d = log2_[dfn[y] - dfn[x] + 1];
    return gmin(st[d][dfn[x]], st[d][dfn[y] - (1 << d) + 1]);
}

void pushup(int p)
{
    nodes[p].sum = nodes[nodes[p].lson].sum + nodes[nodes[p].rson].sum - dep[getLCA(nodes[nodes[p].lson].t, nodes[nodes[p].rson].s)];
    nodes[p].s = (nodes[nodes[p].lson].s ? nodes[nodes[p].lson].s : nodes[nodes[p].rson].s);
    nodes[p].t = (nodes[nodes[p].rson].t ? nodes[nodes[p].rson].t : nodes[nodes[p].lson].t);
}

#define mid ((l + r) >> 1)

int update(int qx, int l, int r, int p, int val)
{
    if (p == 0)
        p = ++ptot;
    if (l == r)
    {
        nodes[p].val += val;
        if (nodes[p].val > 0)
            nodes[p].s = nodes[p].t = qx, nodes[p].sum = dep[qx];
        else
            nodes[p].s = nodes[p].t = nodes[p].sum = 0;
        return p;
    }
    if (dfn[qx] <= mid)
        nodes[p].lson = update(qx, l, mid, nodes[p].lson, val);
    else
        nodes[p].rson = update(qx, mid + 1, r, nodes[p].rson, val);
    pushup(p);
    return p;
}

int query(int p) { return nodes[p].sum - dep[getLCA(nodes[p].s, nodes[p].t)]; }

int merge(int x, int y, int l, int r)
{
    if (x == 0 || y == 0)
        return x + y;
    if (l == r)
    {
        nodes[x].val += nodes[y].val, nodes[x].sum |= nodes[y].sum;
        nodes[x].s |= nodes[y].s, nodes[x].t |= nodes[y].t;
        return x;
    }
    nodes[x].lson = merge(nodes[x].lson, nodes[y].lson, l, mid);
    nodes[x].rson = merge(nodes[x].rson, nodes[y].rson, mid + 1, r);
    pushup(x);
    return x;
}

void solve(int u, int fa)
{
    for (int i = head[u]; i != -1; i = edges[i].nxt)
        if (edges[i].to != fa)
            solve(edges[i].to, u);
    for (int v : remTag[u])
        roots[u] = update(v, 1, stot, roots[u], -1);
    ans += query(roots[u]), roots[up[u]] = merge(roots[up[u]], roots[u], 1, stot);
}

int main()
{
    memset(head, -1, sizeof(head));
    scanf("%d%d", &n, &m);
    for (int i = 1, u, v; i <= n - 1; i++)
        scanf("%d%d", &u, &v), addpath(u, v), addpath(v, u);
    dfs(1, 0);
    for (int i = 2; i <= stot; i++)
        log2_[i] = log2_[i >> 1] + 1;
    for (int i = 1; i < 20; i++)
        for (int j = 1; j + (1 << i) - 1 <= stot; j++)
            st[i][j] = gmin(st[i - 1][j], st[i - 1][j + (1 << (i - 1))]);
    for (int i = 1, u, v, lca; i <= m; i++)
    {
        scanf("%d%d", &u, &v), lca = getLCA(u, v);
        roots[u] = update(u, 1, stot, roots[u], 1), roots[u] = update(v, 1, stot, roots[u], 1);
        roots[v] = update(u, 1, stot, roots[v], 1), roots[v] = update(v, 1, stot, roots[v], 1);
        remTag[lca].push_back(u), remTag[lca].push_back(v);
        remTag[up[lca]].push_back(u), remTag[up[lca]].push_back(v);
    }
    solve(1, 0), printf("%lld\n", ans >> 1);
    return 0;
}
```
