a527困難枚舉十個字母的大小寫選擇後 BFS

CPE:Letters (UVa 12797)

把路徑相容性改成全域遮罩,避免搜尋所有走法。

前往題目練習 →回報教學錯誤最壞時間 O(2¹⁰N²),空間 O(N²)。

解題思路

每個字母只有小寫或大寫二選一,總共 2¹⁰=1024 種配置。對某個遮罩,把大小寫不符的格子視為牆,從左上角執行 BFS。任何一致路徑都能補成其中一種配置;反過來,配置下的每條路徑都不會混用大小寫,所以枚舉不會漏解。

BFS 距離起點設為 1,因為題目數的是經過格子而非邊。起點或終點被遮罩禁用時直接略過。可先讓遮罩符合起終點,再搜尋;若答案已達 2N−1 的曼哈頓下界便停止。多筆 N 與方格讀至 EOF,完全不可達輸出 -1。

Step-by-step animation

示意:2×2 方格 ab/AB

回報動畫錯誤
步驟 1 / 3

固定起終點

起點 a 要求 a 小寫,終點 B 要求 b 大寫。

a
b
A
B
a 位
0
b 位
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    while (cin >> n) {
        vector<string> g(n);
        for (auto &s : g)
            cin >> s;
        vector<int> bit(n * n), upper(n * n);
        for (int r = 0; r < n; ++r)
            for (int c = 0; c < n; ++c) {
                char ch = g[r][c];
                upper[r * n + c] = (ch >= 'A' && ch <= 'J');
                bit[r * n + c] = 1 << (upper[r * n + c] ? ch - 'A' : ch - 'a');
            }
        int best = 1000000000;
        for (int mask = 0; mask < 1024; ++mask) {
            auto ok = [&](int v) { return bool(mask & bit[v]) == bool(upper[v]); };
            if (!ok(0) || !ok(n * n - 1))
                continue;
            vector<int> d(n * n, 0);
            queue<int> q;
            d[0] = 1;
            q.push(0);
            while (!q.empty()) {
                int v = q.front();
                q.pop();
                if (v == n * n - 1) {
                    best = min(best, d[v]);
                    break;
                }
                int r = v / n, c = v % n;
                for (auto [dr, dc] : vector<pair<int, int>>{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}) {
                    int x = r + dr, y = c + dc;
                    if (x < 0 || x >= n || y < 0 || y >= n)
                        continue;
                    int u = x * n + y;
                    if (!d[u] && ok(u)) {
                        d[u] = d[v] + 1;
                        q.push(u);
                    }
                }
            }
            if (best == 2 * n - 1)
                break;
        }
        cout << (best == 1000000000 ? -1 : best) << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多