题解:P1713 麦当劳叔叔的难题

· · 题解

直入主题,这是一道思路极简,难度全在实现上的黑题。其本质是在一张带有障碍物的网格图中求一次起点到终点的最短简单路径和一次最长简单路径。

对于最短简单路径,我们只需要进行一次 BFS,在终点第一次被 BFS 到的时候返回距离就行了,这个操作是 O(n^2) 的,对于这题的 n\le10,几乎可以看作是零成本的操作。

对于最长简单路径,这就是本题的核心难点了,如果使用暴力 DFS 的话,复杂度是 O(4^{n^2}),在本题的数据规模下完全不可接受。

分析或是直接看标签可知本题的正解其实是轮廓线 DP(插头 DP),可以将求解本题的复杂度暴降至 O(n^23^n) 。

首先将整个网格上下镜像一下,起点和终点就变成了更符合直觉的左上到右下,然后我们按照从左到右、由上而下的次序遍历整个网格,以一个 5 × 5 没有障碍物的简单矩阵为例,当遍历到 (1,2) 时,矩阵的状态是这样的(绿色为已处理,蓝色为当前,白色为未处理):

我们将绿色区域与白色或蓝色区域的 分界线定义为处理该格前的轮廓线;白色区域与绿色或蓝色区域的分界线定义为处理该格后的轮廓线, 可以看到对于网格内的任意 (i,j),处理前后的轮廓线都是长 n+1 的。

重点来了,我们现在可以根据路径经过轮廓线的状态来记录这条路径(键),以及达成当前轮廓线状态的路径在已处理区域中可经过的最长长度(值),我们的 DP 过程就是在将其补全为完整的路径。

定义一个 n+1 位的三进制码,对于其的每一位,都可以对应到我们前述的轮廓线中,其每一位也可以被称为一个插头状态:

$1$ 表示**由内向外**(未处理区域)穿过这段轮廓线, $2$ 表示**由外向内**(已处理区域)穿过这段轮廓线。 因为三进制对于计算机并不友好,所以我们使用两个二进制位(即四进制,但四进制的 $3$ 我们是不用的),因此我们可以通过简单的位运算操作来获取或是修改每一位(对应了后面代码中的两个宏函数)。 在处理每一格时,我们需要进行如下工作: 1. 转移已有状态/创造新状态(即 DP 中的递推); 2. 按照新轮廓线状态记录路径。在原轮廓线中,第 $j$ 位是当前方块的左边缘,第 $j+1$ 位是当前方块的上边缘;在新轮廓线中,第 $j$ 位是当前方块的下边缘,第 $j+1$ 位是当前方块的右边缘。 我们定义两个哈希表 **cur**, **nxt**,在处理每个格子前交换二者,并清空 **nxt**, 在处理 $(i,j)$ 时,对于 **cur** 中每一条被记录过的路径,落实到实现上就是: 1. 获取第 $j$ 位和第 $j+1$ 位,分别对应 $(i,j)$ 的左边缘和上边缘的插头,记为 **left** 和 **up**; 2. 分类讨论 **left** 和 **up** 的值:当二者都为 $0$ 时,创建右边缘和下边缘的双向新路径段;二者有一个不为 $0$,另一个为 $0$ 时,转移状态;二者都不为 $0$,且二者不相等,闭合路径; 3. 将产生的新状态写入 **nxt** 哈希表。 在处理完每一行后,我们需要进行行末转移,因为处理完本行最后一格的轮廓线是这样的: ![](https://cdn.luogu.com.cn/upload/image_hosting/uyaidzpc.png) 而下一行的的轮廓线是这样的: ![](https://cdn.luogu.com.cn/upload/image_hosting/ol470kol.png) 转移方法就是将状态码都向后移 $1$ 位,舍弃高位。(具体实现对应到代码中的 **shift** 函数) 如果你这么去试了,那么你可以拿到 $95$ 分,剩下的 $5$ 分困扰了本蒟蒻两天,最后通过随机生成找出了一组 **hack 数据**,画成图就是这样(灰色为障碍物): ![](https://cdn.luogu.com.cn/upload/image_hosting/gj0l4tem.png) 然后**最终提交**的最长路径是: ![](https://cdn.luogu.com.cn/upload/image_hosting/j8w0mm0o.png) 最终路径中出现了一段**环路**,这恰恰是我们当前方法无法避免的。 那么,环路是怎么形成的? 在前面提到的“二者都不为 $0$,且二者不相等,闭合路径”中**连接两个已经在已处理区域内连通的插头时**,那么就形成了环路。 如何避免这种情况?事实上并不需要在我们现在的架构上大动干戈,环路问题实际上可以通过规则极简的**括号匹配**来规避。 将“二者都为 $0$ 时,创建双向路径”改为只创建**下-右**的单向路径,然后我们可以将创建的两个插头分别看作左右括号, 在处理到 **left** 和 **up** 的插头状态相同时,我们不忽略状态,而是反转一个插头使其转换为**下-右**的路径,我们可以通过括号匹配法则轻松找到与其匹配的插头并进行一并反转; 在闭合路径时,我们可以闭合**左-上**的路径,因为这是不会于**下-右**的路径形成环路的,而对于**上-左**的路径,根据括号匹配法则,其必然匹配,闭合会形成环路,忽略该情况。 然后再加上边界检查和入口(我这里设置成了从 $(0,0)$ 左侧进入)和出口(我这里设置成了从 $(n-1,n-1)$ 下方离开)就搞定了。 至此,本题毕,附上代码: ```cpp #include <iostream> #include <vector> #include <queue> #include <unordered_map> using namespace std; typedef pair<int, int> pii; class Solution { private: //四进制操作函数 constexpr int get_plug(int s, int pos) { return (s >> (pos << 1)) & 3; } constexpr int set_plug(int s, int pos, int val) { int shift = (pos << 1); return (s & ~(3 << shift)) | (val << shift); } constexpr int shift(int s) { int mod = 1 << ((n + 1) << 1); return (s << 2) & (mod - 1); } //括号操作 inline int find_match_r(int s, int pos) { int cnt = 1; for (int i = pos - 1; i >= 0; i--) { if (get_plug(s, i) == 1) cnt--; else if (get_plug(s, i) == 2) cnt++; if (!cnt) { return i; } } return -1; } inline int find_match_l(int s, int pos) { int cnt = 1; for (int i = pos + 1; i <= n; i++) { if (get_plug(s, i) == 1) cnt++; else if (get_plug(s, i) == 2) cnt--; if (!cnt) { return i; } } return -1; } private: vector<pii> nodes; vector<vector<char>> matrix; vector<vector<int>> graph; int n, G_size; void BuildMatrix() { matrix.resize(n, vector<char>(n, false)); for (const auto& [x, y] : nodes) { matrix[n - 1 - x][y] = true; } return; } void BuildGraph() { graph.resize(G_size); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { pii neighbors[4] = { {i, j - 1},{i, j + 1}, {i - 1, j}, {i + 1, j} }; for (const auto& [x, y] : neighbors) { if (x >= 0 && x < n && y >= 0 && y < n && !matrix[x][y]) { graph[i * n + j].push_back(x * n + y); } } } } return; } int start, end; int ShortestPath() { queue<int> q; q.push(start); vector<int> level(G_size, -1); level[start] = 0; while (!q.empty()) { int u = q.front(); q.pop(); for (const int v : graph[u]) { if (level[v] == -1) { level[v] = level[u] + 1; q.push(v); } if (v == end) return level[v]; } } return -1; } int LongestPath() { unordered_map<int, int> cur, nxt; //state_pos每一位状态含义:0为不经过本轮廓线,1为向外穿过,2为向内穿过(内外指已处理区域) //轮廓线的第k位代表自左往右数的第k段,所以共m+1条 //初始状态:由(0,0)上方穿入网格 int first_state = set_plug(0, 0, 1); nxt[first_state] = 0; auto renew_state = [&](int i_s, int i_val) { nxt[i_s] = max(nxt[i_s], i_val); }; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cur.swap(nxt); nxt.clear(); for (const auto [s, val] : cur) { int left = get_plug(s, j), up = get_plug(s, j + 1); if (matrix[i][j]) { if (left == 0 && up == 0) { renew_state(s, val); } continue; } if (left == 0 && up == 0) { //原路径写回 renew_state(s, val); //开启新路径 if (i != n - 1 && j != n - 1) { int new_s = set_plug(s, j, 1); new_s = set_plug(new_s, j + 1, 2); renew_state(new_s, val + 1); } } else if (left != 0 && up == 0) { //向右转移 if (j != n - 1) { int new_s = set_plug(s, j, 0); new_s = set_plug(new_s, j + 1, left); renew_state(new_s, val + 1); } //向下转移 if (i != n - 1 || j == n - 1) { renew_state(s, val + 1); } } else if (left == 0 && up != 0) { //向右转移 if (j != n - 1) { renew_state(s, val + 1); } //向下转移 if (i != n - 1 || j == n - 1) { int new_s = set_plug(s, j + 1, 0); new_s = set_plug(new_s, j, up); renew_state(new_s, val + 1); } } else if (left == 1 && up == 1) { //反转上插头的匹配括号 int match_plug = find_match_l(s, j + 1); int new_s = set_plug(s, match_plug, 1); //消除插头 new_s = set_plug(new_s, j, 0); new_s = set_plug(new_s, j + 1, 0); renew_state(new_s, val + 1); } else if (left == 2 && up == 2) { //反转左插头的匹配括号 int match_plug = find_match_r(s, j); int new_s = set_plug(s, match_plug, 2); //消除插头 new_s = set_plug(new_s, j, 0); new_s = set_plug(new_s, j + 1, 0); renew_state(new_s, val + 1); } else if (left == 2 && up == 1) { //直接匹配 int new_s = set_plug(s, j, 0); new_s = set_plug(new_s, j + 1, 0); renew_state(new_s, val + 1); } } } //行末转移 cur.swap(nxt); nxt.clear(); for (const auto [s, val] : cur) { int new_s = shift(s); nxt[new_s] = val; } } int final_state = set_plug(0, n, 1); return nxt[final_state] - 1; } public: Solution(const int ln, vector<pii>& ind) { n = ln; nodes.swap(ind); G_size = n * n; start = 0; end = G_size - 1; BuildMatrix(); } int solve() { BuildGraph(); int min_dist = ShortestPath(); int max_dist = LongestPath(); return max_dist - min_dist; } }; int main() { int n, m; cin >> n >> m; vector<pii> nodes; nodes.reserve(m); while (m--) { int x, y; cin >> x >> y; nodes.emplace_back(x - 1, y - 1); } Solution proj(n, nodes); cout << proj.solve() << endl; return 0; } ``` 但反复的清空和遍历,且无需删除元素导致和 **std::unordered_map** 的相性不佳,这里 **C++23 O2** 只能跑 400ms ,下面是一个换了本人自制的类扁平哈希的版本: ```cpp #include <iostream> #include <vector> #include <array> #include <queue> #include <memory> #include <unordered_map> using namespace std; class FlatHashMap { private: typedef pair<int, int> pkv; struct BarrelNode { static const size_t SIZE_ARR = 2; size_t size; pkv arr[SIZE_ARR]; unique_ptr<vector<pkv>> vec; BarrelNode() : size(0), vec(nullptr) { } pkv* at(size_t pos) { if (pos >= size) return nullptr; if (pos < SIZE_ARR) return &arr[pos]; size_t pos_invec = pos - SIZE_ARR; return vec->data() + pos_invec; } inline void push_back(const pkv& val) { if (size < SIZE_ARR) { arr[size++] = val; return; } if (vec.get() == nullptr) vec = make_unique<vector<pkv>>(); vec->push_back(val); size++; return; } inline void push_pkv(const pkv& val) { for (size_t i = 0; i < min(SIZE_ARR, size); i++) { if (arr[i].first == val.first) { arr[i].second = max(arr[i].second, val.second); return; } } if (size > SIZE_ARR) { for (auto& [k, v] : *vec) { if (k == val.first) { v = max(v, val.second); return; } } } push_back(val); return; } inline int find_val(int key) { for (size_t i = 0; i < SIZE_ARR; i++) { if (arr[i].first == key) { return arr[i].second; } } if (size > SIZE_ARR) { for (auto& [k, v] : *vec) { if (k == key) { return v; } } } return -1; } }; constexpr size_t calc_hash(int mykey) { size_t skey = (size_t)mykey ^ (size_t)mykey >> 32; return skey ^ (skey >> 16); } constexpr size_t select_barrel(int mykey) { return calc_hash(mykey) & (size - 1); } public: size_t size; vector<BarrelNode> bars; public: FlatHashMap(const size_t isz) : size(2) { size_t temp = isz; while (temp >>= 1) size <<= 1; if (size == (isz << 1)) size = isz; bars.resize(size); } struct iterator { FlatHashMap* prt; BarrelNode* bar; size_t pos; iterator(FlatHashMap* const iprt, BarrelNode* ibr, size_t ipos = 0) : prt(iprt), bar(ibr), pos(ipos) { } iterator& operator++() { pos++; if (pos >= bar->size) { pos = 0; bar++; while (bar != prt->bars.data() + prt->size && bar->size == 0) bar++; } return *this; } pkv* operator->() { return bar->at(pos); } pkv& operator*() { return *(bar->at(pos)); } bool operator!=(const iterator& other) { return prt != other.prt || bar != other.bar || pos != other.pos; } }; inline iterator begin() { iterator res(this, bars.data(), 0); if (res.bar != bars.data() + size && bars[0].size == 0) ++res; return res; } inline iterator end() { return iterator(this, bars.data() + size, 0); } inline void insert(const pkv& val) { bars[select_barrel(val.first)].push_pkv(val); } inline void clear() { for (BarrelNode& brr : bars) { brr.size = 0; if (brr.vec.get() != nullptr) brr.vec->clear(); } return; } inline int find_val(int key) { return bars[select_barrel(key)].find_val(key); } }; typedef pair<int, int> pii; class Solution { private: //四进制操作函数 constexpr int get_plug(int s, int pos) { return (s >> (pos << 1)) & 3; } constexpr int set_plug(int s, int pos, int val) { int shift = (pos << 1); return (s & ~(3 << shift)) | (val << shift); } constexpr int shift(int s) { int mod = 1 << ((n + 1) << 1); return (s << 2) & (mod - 1); } //括号操作 inline int find_match_r(int s, int pos) { int cnt = 1; for (int i = pos - 1; i >= 0; i--) { if (get_plug(s, i) == 1) cnt--; else if (get_plug(s, i) == 2) cnt++; if (!cnt) { return i; } } return -1; } inline int find_match_l(int s, int pos) { int cnt = 1; for (int i = pos + 1; i <= n; i++) { if (get_plug(s, i) == 1) cnt++; else if (get_plug(s, i) == 2) cnt--; if (!cnt) { return i; } } return -1; } private: vector<pii> nodes; vector<vector<char>> matrix; vector<vector<int>> graph; int n, G_size; void BuildMatrix() { matrix.resize(n, vector<char>(n, false)); for (const auto& [x, y] : nodes) { matrix[n - 1 - x][y] = true; } return; } void BuildGraph() { graph.resize(G_size); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { pii neighbors[4] = { {i, j - 1},{i, j + 1}, {i - 1, j}, {i + 1, j} }; for (const auto& [x, y] : neighbors) { if (x >= 0 && x < n && y >= 0 && y < n && !matrix[x][y]) { graph[i * n + j].push_back(x * n + y); } } } } return; } int start, end; int ShortestPath() { queue<int> q; q.push(start); vector<int> level(G_size, -1); level[start] = 0; while (!q.empty()) { int u = q.front(); q.pop(); for (const int v : graph[u]) { if (level[v] == -1) { level[v] = level[u] + 1; q.push(v); } if (v == end) return level[v]; } } return -1; } int LongestPath() { FlatHashMap roll_hash[2] = { FlatHashMap(4 << n) , FlatHashMap(4 << n) }; //state_pos每一位状态含义:0为不经过本轮廓线,1为向外穿过,2为向内穿过(内外指已处理区域) //轮廓线的第k位代表自左往右数的第k段,所以共m+1条 size_t cur = 0, nxt = 1; //初始状态:由(0,0)上方穿入网格 int first_state = set_plug(0, 0, 1); roll_hash[nxt].insert(make_pair(first_state, 0)); auto renew_state = [&](int i_s, int i_val) { roll_hash[nxt].insert(make_pair(i_s, i_val)); }; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { swap(cur, nxt); roll_hash[nxt].clear(); for (const auto [s, val] : roll_hash[cur]) { int left = get_plug(s, j), up = get_plug(s, j + 1); if (matrix[i][j]) { if (left == 0 && up == 0) { renew_state(s, val); } continue; } if (left == 0 && up == 0) { //原路径写回 renew_state(s, val); //开启新路径 if (i != n - 1 && j != n - 1) { int new_s = set_plug(s, j, 1); new_s = set_plug(new_s, j + 1, 2); renew_state(new_s, val + 1); } } else if (left != 0 && up == 0) { //向右转移 if (j != n - 1) { int new_s = set_plug(s, j, 0); new_s = set_plug(new_s, j + 1, left); renew_state(new_s, val + 1); } //向下转移 if (i != n - 1 || j == n - 1) { renew_state(s, val + 1); } } else if (left == 0 && up != 0) { //向右转移 if (j != n - 1) { renew_state(s, val + 1); } //向下转移 if (i != n - 1 || j == n - 1) { int new_s = set_plug(s, j + 1, 0); new_s = set_plug(new_s, j, up); renew_state(new_s, val + 1); } } else if (left == 1 && up == 1) { //反转上插头的匹配括号 int match_plug = find_match_l(s, j + 1); int new_s = set_plug(s, match_plug, 1); //消除插头 new_s = set_plug(new_s, j, 0); new_s = set_plug(new_s, j + 1, 0); renew_state(new_s, val + 1); } else if (left == 2 && up == 2) { //反转左插头的匹配括号 int match_plug = find_match_r(s, j); int new_s = set_plug(s, match_plug, 2); //消除插头 new_s = set_plug(new_s, j, 0); new_s = set_plug(new_s, j + 1, 0); renew_state(new_s, val + 1); } else if (left == 2 && up == 1) { //直接匹配 int new_s = set_plug(s, j, 0); new_s = set_plug(new_s, j + 1, 0); renew_state(new_s, val + 1); } } } //行末转移 swap(cur, nxt); roll_hash[nxt].clear(); for (const auto [s, val] : roll_hash[cur]) { int new_s = shift(s); renew_state(new_s, val); } } int final_state = set_plug(0, n, 1); return roll_hash[nxt].find_val(final_state) - 1; } public: Solution(const int ln, vector<pii>& ind) { n = ln; nodes.swap(ind); G_size = n * n; start = 0; end = G_size - 1; BuildMatrix(); } int solve() { BuildGraph(); int min_dist = ShortestPath(); int max_dist = LongestPath(); return max_dist - min_dist; } }; int main() { int n, m; cin >> n >> m; vector<pii> nodes; nodes.reserve(m); while (m--) { int x, y; cin >> x >> y; nodes.emplace_back(x - 1, y - 1); } Solution proj(n, nodes); cout << proj.solve() << endl; return 0; } ``` C++23 **O2** 能跑 [191ms](https://www.luogu.com.cn/record/259610526),应该性能压榨得差不多了。