a435中等排列分解・走訪環

APCS 2017/03:小群體 (ZeroJudge c291)

用 visited 陣列沿好友關係走訪,每走完一圈就找到一個小群體。

前往題目練習 →回報教學錯誤時間 O(n) ・ 空間 O(n)

這題在學什麼

每個人恰好指向一位好友,而且每個編號恰好出現一次,所以好友關係是一個排列。排列中的每個連通部分必然是一個環。

從尚未拜訪的人開始,沿著好友指標前進並標記 visited,直到回到已拜訪的人。這整段恰好是一個群體;再找下一個未拜訪的人即可。

Step-by-step animation

好友指標

回報動畫錯誤
步驟 1 / 3

從 0 開始

沿好友關係 0→4→6→8→5→0,走回已拜訪的 0,一圈完成。

0→4
4→6
6→8
8→5
5→0
群體數
1
已拜訪
0,4,5,6,8

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> friendOf(n);
    for (int& x : friendOf) cin >> x;

    vector<bool> visited(n, false);
    int groups = 0;
    for (int start = 0; start < n; ++start) {
        if (visited[start]) continue;
        ++groups;
        int current = start;
        while (!visited[current]) {
            visited[current] = true;
            current = friendOf[current];
        }
    }
    cout << groups << '\n';
}

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

更多