a706簡單四鄰接連通區塊與雙鍵排名

CPE:Rank the Languages (UVa 10336)

每次洪水填色只增加一個國家,再按數量排序語言。

前往題目練習 →回報教學錯誤時間 O(HW+26 log26),空間 O(HW)。

解題思路

逐格掃描,遇到尚未走訪的字母ch,就找到一個新國家,該語言計數加1。以堆疊或佇列走訪同字母的上下左右相鄰格,入列時立即標記,將整個連通區都消掉;這能保證同國家不會再被掃描計數。

掃描結束後,依國家數遞減排序,數量相同依字母遞增。不同地區即使字母相同,只要沒有四鄰接路徑就算不同國家;對角相碰不連接。輸出先印World #k,接著每個出現字母的 ch: 數量,不加多餘案例空行。使用迭代走訪避免大地圖遞迴堆疊限制。

Step-by-step animation

示意:2×3地圖 aba / aaa

回報動畫錯誤
步驟 1 / 3

找到a

從左上a出發,沿下排連到右上a。

a b a
a a a
a國家
1
a格數
5

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main() {
    int tests;
    cin >> tests;
    for (int tc = 1; tc <= tests; tc++) {
        int h, w;
        cin >> h >> w;
        vector<string> a(h);
        for (auto &s : a)
            cin >> s;
        int count[26] = {};
        int dr[] = {-1, 1, 0, 0}, dc[] = {0, 0, -1, 1};
        for (int r = 0; r < h; r++)
            for (int c = 0; c < w; c++)
                if (a[r][c] != '#') {
                    char ch = a[r][c];
                    count[ch - 'a']++;
                    vector<pair<int, int>> stack{{r, c}};
                    a[r][c] = '#';
                    while (!stack.empty()) {
                        auto [x, y] = stack.back();
                        stack.pop_back();
                        for (int d = 0; d < 4; d++) {
                            int nr = x + dr[d], nc = y + dc[d];
                            if (nr >= 0 && nr < h && nc >= 0 && nc < w && a[nr][nc] == ch) {
                                a[nr][nc] = '#';
                                stack.push_back({nr, nc});
                            }
                        }
                    }
                }
        vector<pair<int, char>> ranking;
        for (int i = 0; i < 26; i++)
            if (count[i])
                ranking.push_back({-count[i], char('a' + i)});
        sort(ranking.begin(), ranking.end());
        cout << "World #" << tc << '\n';
        for (auto [v, ch] : ranking)
            cout << ch << ": " << -v << '\n';
    }
}

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

更多