P9698 [GDCPC 2023] Path Planning

题目描述

有一个 $n$ 行 $m$ 列的网格。网格里的每个格子都写着一个整数,其中第 $i$ 行第 $j$ 列的格子里写着整数 $a_{i, j}$。从 $0$ 到 $(n \times m - 1)$ 的每个整数(含两端)在网格里都恰好出现一次。 令 $(i, j)$ 表示位于第 $i$ 行第 $j$ 列的格子。您现在需要从 $(1, 1)$ 出发并前往 $(n, m)$。当您位于格子 $(i, j)$ 时,您可以选择走到右方的格子 $(i, j + 1)$(若 $j < m$),也可以选择走到下方的格子 $(i + 1, j)$(若 $i < n$)。 令 $\mathbb{S}$ 表示路径上每个格子里的整数形成的集合,包括 $a_{1, 1}$ 和 $a_{n, m}$。令 $\text{mex}(\mathbb{S})$ 表示不属于 $\mathbb{S}$ 的最小非负整数。请找出一条路径以最大化 $\text{mex}(\mathbb{S})$,并求出这个最大的值。

输入格式

有多组测试数据。第一行输入一个整数 $T$ 表示测试数据组数。对于每组测试数据: 第一行输入两个整数 $n$ 和 $m$($1 \le n, m \le 10^6$,$1 \le n \times m \le 10^6$)表示网格的行数和列数。 对于接下来 $n$ 行,第 $i$ 行输入 $m$ 个整数 $a_{i, 1}, a_{i, 2}, \cdots, a_{i, m}$($0 \le a_{i, j} < n \times m$),其中 $a_{i, j}$ 表示格子 $(i, j)$ 里的整数。从 $0$ 到 $(n \times m - 1)$ 的每个整数(含两端)在网格里都恰好出现一次。 保证所有数据 $n \times m$ 之和不超过 $10^6$。

输出格式

每组数据输出一行一个整数,表示最大的 $\text{mex}(\mathbb{S})$。 **【样例解释】** 对于第一组样例数据,共有 $3$ 条可能的路径。 - 第一条路径为 $(1, 1) \to (1, 2) \to (1, 3) \to (2, 3)$。$\mathbb{S} = \{1, 2, 4, 5\}$ 因此 $\text{mex}(\mathbb{S}) = 0$。 - 第二条路径为 $(1, 1) \to (1, 2) \to (2, 2) \to (2, 3)$。$\mathbb{S} = \{1, 2, 0, 5\}$ 因此 $\text{mex}(\mathbb{S}) = 3$。 - 第三条路径为 $(1, 1) \to (2, 1) \to (2, 2) \to (2, 3)$。$\mathbb{S} = \{1, 3, 0, 5\}$ 因此 $\text{mex}(\mathbb{S}) = 2$。 因此答案为 $3$。 对于第二组样例数据,只有 $1$ 条可能的路径,即 $(1, 1) \to (1, 2) \to (1, 3) \to (1, 4) \to (1, 5)$。$\mathbb{S} = \{1, 3, 0, 4, 2\}$ 因此 $\text{mex}(\mathbb{S}) = 5$。

说明/提示

For the first sample test case there are $3$ possible paths. - The first path is $(1, 1) \to (1, 2) \to (1, 3) \to (2, 3)$. $\mathbb{S} = \{1, 2, 4, 5\}$ so $\text{mex}(\mathbb{S}) = 0$. - The second path is $(1, 1) \to (1, 2) \to (2, 2) \to (2, 3)$. $\mathbb{S} = \{1, 2, 0, 5\}$ so $\text{mex}(\mathbb{S}) = 3$. - The third path is $(1, 1) \to (2, 1) \to (2, 2) \to (2, 3)$. $\mathbb{S} = \{1, 3, 0, 5\}$ so $\text{mex}(\mathbb{S}) = 2$. So the answer is $3$. For the second sample test case there is only $1$ possible path, which is $(1, 1) \to (1, 2) \to (1, 3) \to (1, 4) \to (1, 5)$. $\mathbb{S} = \{1, 3, 0, 4, 2\}$ so $\text{mex}(\mathbb{S}) = 5$.