Attack on Alpha-Zet#11625

Attack on Alpha-Zet (Editorial)

The modules of the maze are connected so that there is exactly one path between any two of them. Hence the maze is a tree: the vertices are modules, and the edges are pairs of adjacent modules not separated by a wall. The tree has h \cdot w \le 10^6 vertices in total.

Parsing the map. Let us number the rows and columns from zero. Then module is described by line g[r + 1] at position 2c + 1. The character at this position is the south wall of the module, and the characters to its left and right are the west and east walls. The north wall of a module coincides with the south wall of the module above it and is located in line at the same position.

Route length. Captain Chris visits the modules v_1, v_2, \ldots, v_m in order, and between consecutive modules of the route he walks along the unique path in the tree. Therefore, the answer is the sum of the distances \mathit{dist}(v_i, v_{i+1}) for i = 1, \ldots, m - 1.

Let us root the tree at module and denote by the depth of vertex . The path from to goes up from to the lowest common ancestor \mathit{lca} = \mathit{LCA}(a, b) and then goes down to . Hence

\mathit{dist}(a, b) = \mathit{depth}[a] + \mathit{depth}[b] - 2 \cdot \mathit{depth}[\mathit{lca}]

Depths and parents. The tree can have up to 10^6 vertices, and its depth can be of the same order, for example in a "snake" maze. A recursive depth-first search on such a tree may overflow the stack, so we compute depths and parents with a breadth-first search from the root. Since the path to the root in a tree is unique, the depth found by the breadth-first search equals the depth in the tree.

Finding the LCA. We use the binary lifting method. For each vertex we store \mathit{up}[v][k] — its ancestor 2^k levels higher. To find \mathit{LCA}(a, b), we first lift the deeper vertex to the depth of the other one, decomposing the depth difference into powers of two. If the vertices coincide, the answer is found. Otherwise, we lift both vertices simultaneously with jumps from long to short while their ancestors differ. In the end, both vertices are children of the LCA.

The answer can reach (m - 1) \cdot h \cdot w \approx 10^{10}, so it must be stored in a -bit type.

Complexity. The breadth-first search runs in , filling the lifting table takes O(hw \log(hw)), and each LCA query takes O(\log(hw)). The total complexity is O((hw + m) \log(hw)). The table contains 10^6 \cdot 20 integers, that is, about MB.

Example

The maze from the sample has size 2 \times 6. In the top row all modules are connected to each other, and all modules except have a south wall. The bottom row is also fully connected, so the tree looks like a "horseshoe": the top row, the passage — , and the bottom row.

Depths from the root : module has depth y - 1, and module has depth . The root is an ancestor of all vertices, so for every pair of consecutive modules of the route \mathit{lca} = (1, 1) and \mathit{depth}[\mathit{lca}] = 0.

The route length is 4 + 5 + 5 + 4 = 18.

Note that modules and are adjacent but separated by a wall. Their lowest common ancestor is the root, and the distance between them is 5 + 6 - 2 \cdot 0 = 11: the path goes through the whole top row, the passage — , and the whole bottom row.

Let us consider the second example in detail.

Step 1. Parsing the map. The maze has size 5 \times 5. The map occupies h + 1 = 6 lines of 2w + 1 = 11 characters. Module from the statement (numbered from one) is described by line at position 2y - 1 (positions are counted from zero). The character at this position is the south wall of the module, and the characters to its left and right are the west and east walls.

For example, for module the character g[1][1] = "_", so it has a south wall and one cannot go to . The character is a space, there is no east wall, so module is connected to . For module the characters and are "|", while and are spaces: this is a vertical corridor open only to the north and to the south.

Step 2. The tree and the depths. The maze has modules and passages between them, and there are no cycles, so it is a tree. We run a breadth-first search from module and compute for each module its depth — the number of moves from . The marked modules are labeled with their order numbers in the route: — , — , — , — , — , — , — .

Step 2a. The binary lifting table. In the program, modules are numbered from zero row by row: module from the statement corresponds to vertex v = (x - 1) \cdot w + (y - 1). In the figure, each cell contains the vertex number, and the arrow points to its parent. After the breadth-first search only the column \mathit{up}[v][0] is filled — the immediate parent of vertex . The root is considered to be its own parent: \mathit{up}[0][0] = 0.

The remaining columns are filled by the loop

  for (int k = 1; k < LOG; k++)
    for (int v = 0; v < V; v++)
      up[v][k] = up[up[v][k - 1]][k - 1];

A jump of 2^k levels up is two jumps of 2^{k-1} levels: first from to vertex \mathit{up}[v][k - 1], and then from it another 2^{k-1} levels. The outer loop iterates over , so by the time column is computed, column k - 1 is already completely filled for all vertices, and the order of vertices inside a column does not matter.

Let us analyze the row v = 6 — module at depth , the deepest one in the maze. The chain of its ancestors is: 6 \to 5 \to 10 \to 15 \to 16 \to 17 \to 12 \to 7 \to 2 \to 1 \to 0.

The rows of all vertices are filled in the same way. The maximum depth in the maze is 10 < 2^4, so column k = 4 and all the following ones (up to k = 19, since \mathit{LOG} = 20) contain zeros — any jump of such length leads to the root. The state of the array after the loop:

The table makes it easy to trace the lca function. At step 6 \to 7, after the depths are equalized, the function works with vertices 5 = (2, 1) and 23 = (5, 4). A jump of length leads to the same vertex: \mathit{up}[5][2] = \mathit{up}[23][2] = 17, so it is skipped. A jump of length leads to different vertices \mathit{up}[5][1] = 15 and \mathit{up}[23][1] = 21, so it is performed. A jump of length from and again leads to the same vertex \mathit{up}[15][0] = \mathit{up}[21][0] = 16, so it is skipped. The answer is \mathit{up}[15][0] = 16, that is, module .

Step 3. Distances between consecutive modules of the route. For each pair, we find and compute

\mathit{dist}(a, b) = \mathit{depth}[a] + \mathit{depth}[b] - 2 \cdot \mathit{depth}[\mathit{lca}]

№

from

to

moves

1 \to 2

2 \to 3

3 \to 4

4 \to 5

5 \to 6

6 \to 7

total

Let us look at several steps in more detail.

. From module the path goes up moves to \mathit{lca} = (3, 3) and then goes down moves to through , , , . In total 6 + 9 - 2 \cdot 4 = 7.

. Module is an ancestor of module , so \mathit{lca} = (1, 2) and the path only goes up: 7 - 1 = 6 moves.

. Modules and are adjacent but separated by a wall. Module is an ancestor of , so the path only goes down: from through , along the corridor in the third column to , then left to , and up to and . We get 1 + 10 - 2 \cdot 1 = 9 moves, although the modules are neighbors in a straight line.

. Let us show how the lca function finds the common ancestor of modules a = (2, 2) and b = (5, 4). Their depths are and , so is first lifted by \mathit{diff} = 1 level to . Now both vertices are at depth , but they are different.

The chains of their ancestors: (2, 1) \to (3, 1) \to (4, 1) \to (4, 2) and (5, 4) \to (5, 3) \to (5, 2) \to (4, 2). We try jumps from long to short. Jumps of length 2^k for k \ge 2 lead to the same vertex, so we skip them. A jump of length leads to different vertices and — we perform it. A jump of length from and leads to the same vertex — we skip it. The answer: \mathit{up}[(4, 1)][0] = (4, 2), \mathit{depth} = 6, distance 10 + 9 - 2 \cdot 6 = 7.

Step 4. The answer. We add up the lengths of all parts of the route:

7 + 9 + 5 + 6 + 9 + 7 = \mathbf{43}

Algorithm Implementation

Declare the constants. \mathit{LOG} = 20, since 2^{20} > 10^6: jumps of length 2^{19}, 2^{18}, \ldots, 1 are enough to lift to any depth. is the maximum number of modules.

#define LOG 20          // 2^20 > 10^6 — greater than any tree depth
#define MAXV 1000000   // h * w <= 1000 * 1000

Declare the global variables. The maze map is stored in the array of strings . The array contains the depth of vertex in the tree rooted at module . The arrays and store the entry and exit times of a vertex during the depth-first search, and is the current time. \mathit{up}[v][k] stores the ancestor of vertex located 2^k levels higher.

int h, w, timer_;
vector<string> g;   // ASCII map of the maze: h + 1 lines
int depth_[MAXV];
// entry and exit times of the depth-first search
int d[MAXV], f[MAXV];
// up[v][k] — ancestor of vertex v 2^k levels higher
int up[MAXV][LOG];

The id function returns the number of module . Modules are numbered row by row with numbers from to h \cdot w - 1, coordinates are counted from zero.

int id(int r, int c) { return r * w + c; }

The neighbor function returns the number of the neighbor of module in direction , or if it is impossible to move in this direction. First, we restore the coordinates of the module: r = v / w, c = v \% w. The passage to the north is closed if the character g[r][2c + 1] equals "_" — this is the south wall of the module above. The passage to the south is closed by the south wall g[r + 1][2c + 1]. The passages to the west and to the east are closed if the characters g[r + 1][2c] and g[r + 1][2c + 2] equal "|". The conditions r > 0, r < h - 1, c > 0, and c < w - 1 prevent leaving the maze.

// Neighbor of module v in direction dir
// (0 — north, 1 — south, 2 — west, 3 — east)
// or -1 if it is impossible to move there
int neighbor(int v, int dir)
{
  int r = v / w, c = v % w;
  if (dir == 0 && r > 0 && g[r][2 * c + 1] != '_')
    return id(r - 1, c);
  if (dir == 1 && r < h - 1 && g[r + 1][2 * c + 1] != '_')
    return id(r + 1, c);
  if (dir == 2 && c > 0 && g[r + 1][2 * c] != '|')
    return id(r, c - 1);
  if (dir == 3 && c < w - 1 && g[r + 1][2 * c + 2] != '|')
    return id(r, c + 1);
  return -1;
}

The dfs function performs a depth-first search from vertex . The parameter is the parent of vertex , and is its depth. On entering the vertex, we record its entry time , its depth, and its immediate parent.

void dfs(int v, int p, int len)
{
  d[v] = timer_++;
  depth_[v] = len;
  up[v][0] = p;

Fill the row of the binary lifting table for vertex : the ancestor 2^i levels higher is the ancestor 2^{i-1} levels higher of the ancestor 2^{i-1} levels higher. All ancestors of vertex have already been visited by the search, so their rows of the table are filled by this moment. For the root p = 0, that is, the root is its own parent, and any jump above the root stops at it.

  for (int i = 1; i < LOG; i++)
    up[v][i] = up[up[v][i - 1]][i - 1];

Iterate over the four directions. Every existing neighbor except the parent is a child of — run the search from it at depth \mathit{len} + 1. Since the maze is a tree, has no other visited neighbors. After all children are processed, record the exit time .

  for (int dir = 0; dir < 4; dir++)
  {
    int to = neighbor(v, dir);
    if (to != -1 && to != p) dfs(to, v, len + 1);
  }
  f[v] = timer_++;
}

The Parent function returns true if vertex is an ancestor of vertex (a vertex is considered an ancestor of itself). This holds if and only if the interval [d[b]; f[b]] is nested in the interval [d[a]; f[a]].

int Parent(int a, int b)
{
  return (d[a] <= d[b]) && (f[a] >= f[b]);
}

The LCA function finds the lowest common ancestor of vertices and . If one of the vertices is an ancestor of the other, it is the answer.

int LCA(int a, int b)
{
  if (Parent(a, b)) return a;
  if (Parent(b, a)) return b;

Otherwise, lift vertex with jumps of length 2^{19}, 2^{18}, \ldots, 1, making a jump only if the new vertex is still not an ancestor of . After the loop, is the highest vertex on the path from to the root that is not an ancestor of . Its parent is the LCA.

  for (int i = LOG - 1; i >= 0; i--)
    if (!Parent(up[a][i], b)) a = up[a][i];
  return up[a][0];
}

The main part of the program. Read the maze dimensions and . Then use the getline function to read the rest of the first line, so that the map can then be read line by line.

cin >> h >> w;
string line;
getline(cin, line);              // read the rest of the first line

Read the h + 1 lines of the ASCII map. The lines are read entirely, including spaces.

g.resize(h + 1);
for (int i = 0; i <= h; i++)
  getline(cin, g[i]);

Run the depth-first search from module — it becomes the root of the tree. The root is considered to be its own parent. The search computes the depths, the timestamps , , and the whole table .

// Module (r, c) is in line r + 1, column 2c + 1 (all zero-based).
// Below it, '_' is the south wall;
// to its right, '|' is the east wall.
// The root is module (0, 0); its parent is the root itself.
dfs(0, 0, 0);

Read the number of marked modules . The variable accumulates the route length. It can reach 10^4 \cdot 10^6 = 10^{10}, so we use the long long type. The variable stores the previous marked module.

cin >> m;
long long ans = 0;
int prev = -1;

For each marked module except the first one, add to the answer the length of the path from to . The path goes up from to their lowest common ancestor and down to , so its length is \mathit{depth\_}[\mathit{prev}] + \mathit{depth\_}[v] - 2 \cdot \mathit{depth\_}[\mathit{LCA}(\mathit{prev}, v)].

for (int i = 0; i < m; i++)
{
  cin >> x >> y;
  int v = id(x - 1, y - 1);
  if (prev != -1)
    ans += depth_[prev] + depth_[v] - 2 * depth_[LCA(prev, v)];
  prev = v;
}

Print the route length.

cout << ans << endl;