Official

N - 通貨変換ネットワーク / Currency Conversion Network Editorial by admin Editorial for printing

gpt-5.5-high

Summary

This problem asks us to find the composition of affine transformations \(t \mapsto at+b\) along the unique path between two vertices in a dynamically changing forest.

We use a Link-Cut Tree to perform edge additions, deletions, updates, and path queries quickly.

Analysis

Since the graph is a forest at any point in time, the path between two cities in the same connected component is always uniquely determined.

Each exchange office on the path represents an affine transformation:

\( t \mapsto at + b \)

For example, if we first apply

\( f(t)=a_1t+b_1 \)

and then apply

\( g(t)=a_2t+b_2 \)

we get:

\( g(f(t)) = a_2(a_1t+b_1)+b_2 = a_2a_1t + (a_2b_1+b_2) \)

In other words, the composition of affine transformations is also an affine transformation.

Representing the transformation as a pair \((a,b)\), the composition of “applying \((a_1,b_1)\) first, then \((a_2,b_2)\)” is:

\( (a_2,b_2) \circ (a_1,b_1) = (a_2a_1,\ a_2b_1+b_2) \)

All calculations are performed modulo \(998244353\).


Naively searching for the path using DFS/BFS for each query would take \(O(N)\) time per query. Since \(N,Q \leq 5 \times 10^4\), the worst-case time complexity would be \(O(NQ)\), which is too slow.

Also, while a Union-Find tree can handle edge additions, it is insufficient here because we need to support edge deletions and path queries.

Therefore, we use a Link-Cut Tree, which can handle dynamic trees.

Algorithm

1. Representing Edges as Vertices

A Link-Cut Tree is fundamentally a data structure that “associates values with vertices.”

In this problem, the exchange offices (i.e., edges) have transformations associated with them. Thus, we represent each edge as a new vertex.

When creating an exchange office between city \(u\) and city \(v\), we create an edge node \(e\) and connect them as:

\( u - e - v \)

City nodes are assigned the identity transformation:

\( t \mapsto t \)

which is \((1,0)\).

For each edge node, based on its direction at the time of creation, we store:

  • forward: the transformation \((a,b)\) from the \(u\)-side to the \(v\)-side
  • reverse: the transformation \((c,d)\) from the \(v\)-side to the \(u\)-side

With this setup, city nodes and edge nodes alternate along the path between cities. Since city nodes represent the identity transformation, they do not affect the result.


2. Managing Path Transformations in the Link-Cut Tree

For each node, we maintain the following values:

  • vfa, vfb: The forward transformation of the node itself
  • vra, vrb: The reverse transformation of the node itself
  • afa, afb: The composed transformation when viewing the splay tree subtree from left to right
  • ara, arb: The composed transformation when viewing the splay tree subtree from right to left

The forward composition is in the order of:

\( \text{right} \circ \text{node} \circ \text{left} \)

Since we also need to view the path in reverse, we maintain the reverse composition simultaneously.

In a Link-Cut Tree, the direction of a path can be reversed by a makeroot operation. Therefore, during a reversal operation, we need to:

  • Swap the left and right children
  • Swap the forward and reverse aggregates
  • Swap the node’s own forward and reverse values

3. Handling Each Operation

L u v a b c d

Create a new edge node \(e\).

Assign the following to the edge node \(e\):

  • forward: \((a,b)\)
  • reverse: \((c,d)\)

Then, connect them on the Link-Cut Tree as \(u - e - v\).

Additionally, we maintain a dictionary to look up the edge node ID \(e\) from the city pair \((u,v)\) so that we can find this edge during C or U operations later.

Since the order of \(u\) and \(v\) in C u v or U u v queries in the input might differ from the order at the time of creation, we store the dictionary keys as unordered pairs.


C u v

Retrieve the corresponding edge node \(e\) from the dictionary.

Since the edge node is inserted between cities \(u\) and \(v\):

  • Cut the connection between \(e\) and one of the endpoints at creation
  • Cut the connection between \(e\) and the other endpoint

This removes the exchange office.


U u v a b c d

Retrieve the corresponding edge node \(e\) and update its transformation.

Note that the given \((a,b)\) and \((c,d)\) in the update are based on the “direction at the time of creation.”

On the other hand, within the Link-Cut Tree, the forward and reverse directions of the edge node might have been swapped due to the reversal from makeroot operations.

Therefore, in the code, we use ori[e] to keep track of whether the current orientation of the edge node is the same as or reversed from the creation time.

  • If ori[e] == 0:
    Set forward to \((a,b)\) and reverse to \((c,d)\)
  • If ori[e] == 1:
    Set forward to \((c,d)\) and reverse to \((a,b)\)

Q x y s

First, if \(x=y\), the path length is 0, so we simply output \(s\).

Otherwise, we check connectivity using findroot in the Link-Cut Tree.

  • If they are not connected, output -1.
  • If they are connected, perform makeroot(x) followed by access(y).

This represents the path from \(x\) to \(y\) as a single splay tree.

At this point, the forward aggregate

\( (A,B) \)

stored at the root \(y\) is the transformation of the entire path from \(x\) to \(y\).

Thus, the answer is:

\( As+B \pmod{998244353} \)

Complexity

  • Time Complexity: \(O(Q \log (N+Q))\)
  • Space Complexity: \(O(N+Q)\)

Each operation in the Link-Cut Tree takes amortized \(O(\log (N+Q))\) time. Since we create a new edge node for each edge addition, the maximum number of nodes is \(N+Q\).

Implementation Details

  • Pay attention to the order of composition of affine transformations. “First \(f\), then \(g\)” is represented as \(g \circ f\).

  • To handle values on edges, we represent each edge as a new node.

  • The transformation of a city node is the identity transformation \((1,0)\).

  • In the reversal process of the Link-Cut Tree, we must swap not only the left and right children but also the forward and reverse transformation aggregates.

  • In the U operation, the updates are given based on the orientation at creation. Therefore, we check the current reversal state ori to decide whether to set them to forward or reverse.

  • In C and U operations, the order of \(u\) and \(v\) in the input may differ from the order at creation. Thus, we use unordered pairs as keys in the dictionary managing the edges.

    Source Code

import sys

MOD = 998244353

input = sys.stdin.buffer.readline
N, Q = map(int, input().split())
MAXM = N + Q + 5
BASE = N + 1

lc = [0] * MAXM
rc = [0] * MAXM
par = [0] * MAXM
rev = [0] * MAXM
ori = [0] * MAXM

vfa = [1] * MAXM
vfb = [0] * MAXM
vra = [1] * MAXM
vrb = [0] * MAXM

afa = [1] * MAXM
afb = [0] * MAXM
ara = [1] * MAXM
arb = [0] * MAXM

eu = [0] * MAXM
ev = [0] * MAXM


def pull(x):
    l = lc[x]
    r = rc[x]

    a = afa[l]
    b = afb[l]
    va = vfa[x]
    vb = vfb[x]
    a = va * a % MOD
    b = (va * b + vb) % MOD
    ra = afa[r]
    rb = afb[r]
    afa[x] = ra * a % MOD
    afb[x] = (ra * b + rb) % MOD

    a = ara[r]
    b = arb[r]
    va = vra[x]
    vb = vrb[x]
    a = va * a % MOD
    b = (va * b + vb) % MOD
    la = ara[l]
    lb = arb[l]
    ara[x] = la * a % MOD
    arb[x] = (la * b + lb) % MOD


def apply_rev(x):
    lc[x], rc[x] = rc[x], lc[x]
    afa[x], ara[x] = ara[x], afa[x]
    afb[x], arb[x] = arb[x], afb[x]
    vfa[x], vra[x] = vra[x], vfa[x]
    vfb[x], vrb[x] = vrb[x], vfb[x]
    rev[x] ^= 1
    ori[x] ^= 1


def push(x):
    if rev[x]:
        l = lc[x]
        r = rc[x]
        if l:
            apply_rev(l)
        if r:
            apply_rev(r)
        rev[x] = 0


def rotate(x):
    p = par[x]
    g = par[p]

    if lc[p] == x:
        b = rc[x]
        rc[x] = p
        lc[p] = b
        if b:
            par[b] = p
    else:
        b = lc[x]
        lc[x] = p
        rc[p] = b
        if b:
            par[b] = p

    par[p] = x
    par[x] = g

    if g:
        if lc[g] == p:
            lc[g] = x
        elif rc[g] == p:
            rc[g] = x

    pull(p)
    pull(x)


def splay(x):
    st = [x]
    y = x
    while True:
        p = par[y]
        if p == 0 or (lc[p] != y and rc[p] != y):
            break
        y = p
        st.append(y)

    for z in reversed(st):
        push(z)

    while True:
        p = par[x]
        if p == 0 or (lc[p] != x and rc[p] != x):
            break
        g = par[p]
        if g != 0 and (lc[g] == p or rc[g] == p):
            if (lc[p] == x) == (lc[g] == p):
                rotate(p)
            else:
                rotate(x)
        rotate(x)


def access(x):
    last = 0
    y = x
    while y:
        splay(y)
        rc[y] = last
        if last:
            par[last] = y
        pull(y)
        last = y
        y = par[y]
    splay(x)


def makeroot(x):
    access(x)
    apply_rev(x)


def findroot(x):
    access(x)
    y = x
    while True:
        push(y)
        l = lc[y]
        if not l:
            break
        y = l
    splay(y)
    return y


def cut(x, y):
    makeroot(x)
    access(y)
    if lc[y] == x:
        lc[y] = 0
        par[x] = 0
        pull(y)


edge = {}
nxt = N + 1
ans = []

for _ in range(Q):
    parts = input().split()
    op = parts[0][0]

    if op == 76:  # L
        u = int(parts[1])
        v = int(parts[2])
        a = int(parts[3])
        b = int(parts[4])
        c = int(parts[5])
        d = int(parts[6])

        e = nxt
        nxt += 1

        lc[e] = rc[e] = par[e] = rev[e] = ori[e] = 0
        vfa[e] = a
        vfb[e] = b
        vra[e] = c
        vrb[e] = d
        afa[e] = a
        afb[e] = b
        ara[e] = c
        arb[e] = d
        eu[e] = u
        ev[e] = v

        if u < v:
            key = u * BASE + v
        else:
            key = v * BASE + u
        edge[key] = e

        makeroot(v)
        par[v] = e
        par[e] = u

    elif op == 67:  # C
        u = int(parts[1])
        v = int(parts[2])
        if u < v:
            key = u * BASE + v
        else:
            key = v * BASE + u

        e = edge.pop(key)
        cut(e, eu[e])
        cut(e, ev[e])

    elif op == 85:  # U
        u = int(parts[1])
        v = int(parts[2])
        a = int(parts[3])
        b = int(parts[4])
        c = int(parts[5])
        d = int(parts[6])

        if u < v:
            key = u * BASE + v
        else:
            key = v * BASE + u

        e = edge[key]
        access(e)

        if ori[e]:
            vfa[e] = c
            vfb[e] = d
            vra[e] = a
            vrb[e] = b
        else:
            vfa[e] = a
            vfb[e] = b
            vra[e] = c
            vrb[e] = d
        pull(e)

    else:  # Q
        x = int(parts[1])
        y = int(parts[2])
        s = int(parts[3])

        if x == y:
            ans.append(str(s))
        elif findroot(x) != findroot(y):
            ans.append("-1")
        else:
            makeroot(x)
            access(y)
            ans.append(str((afa[y] * s + afb[y]) % MOD))

sys.stdout.write("\n".join(ans))

This editorial was generated by gpt-5.5-high.

posted:
last update: