置頂

我的 VPython 教學文件 (HackMD 版本)

VPython 教學文件目錄 安裝及測試 基本語法 等速度直線運動 自由落下 終端速度 水平抛射 使用For迴圈計算水平抛射資料 斜向抛射 圓周運動 簡諧運動 單擺 木塊彈簧系統分離 重力及簡諧 行星運動 相疊木塊 雙重簡諧運動 一維彈性碰撞 ...

熱門文章

2026年11月29日 星期日

LeetCode 解題筆記:2076. Process Restricted Friend Requests

作者:王一哲
日期:2026年11月29日


LeetCode 題目連結:2076. Process Restricted Friend Requests

解題想法


困難題。題目給一個整數 $n ~(2 \leq n \leq 1000)$,代表有 $n$ 個人,編號為 $0$ 到 $n-1$,一開始所有人都不是朋友。再給一個二維陣列 $restrictions$,$restrictions[i] = [x_i, y_i]$,代表 $(x_i, y_i)$ 不能有關係,不論是直接或間接的朋友關係都不行。最後給一個二維陣列 $requests$,$requests[i] = [u_i, v_i]$,代表 $(u_i, v_i)$ 想要成為朋友,但如果 $u_i, v_i$ 各自的朋友群之中有任意兩個人之間存在限制條件,則 $u_i, v_i$ 無法成為朋友。用一個陣列 $ans$ 記錄每一個請求是否能夠達成,如果 $request[i]$ 能夠達成則 $ans[i] = True$,反之 $ans[i] = False$,回傳 $ans$。

這題可以用併查集處理。我的寫法效率比較差,檢查請求中的 $u, v$ 是否能夠合併時,是用 for 迴圈依序檢查 $restrictions$,還有更好的寫法但是我不會寫。

Python 程式碼


Runtime: 1424 ms, beats 58.39%. Memory: 19.80 MB, beats 67.15%.
class DisjointSetUnion:
    def __init__(self, n):
        self.n = n  # 節點數量
        self.parent = list(range(n))  # 根節點
        self.sz = [1] * n  # 區塊大小
        self.restrict = []  # 限制條件
    
    def rfind(self, x):  # 路徑壓縮,找根節點
        if self.parent[x] == x:
            return x
        self.parent[x] = self.rfind(self.parent[x])
        return self.parent[x]
    
    def unite(self, u, v):  # 合併區塊
        root_u, root_v = self.rfind(u), self.rfind(v)
        if root_u != root_v:
            if root_u > root_v:
                root_u, root_v = root_v, root_u
            self.sz[root_u] += self.sz[root_v]
            self.parent[root_v] = root_u
            return True
        return False
    
    def addRestrict(self, u, v):  # 加入限制條件
        self.restrict.append((u, v))

    def canMerge(self, u, v):  # 檢查 u, v 是否可以合併
        root_u, root_v = self.rfind(u), self.rfind(v)
        # u, v 已經在同一個區塊,回傳 True
        if root_u == root_v: return True

        # 依序檢查所有的限制條件,如果 (u, x) 在同一區且 (v, y) 在同一區,
        # 或是 (u, y) 在同一區且 (v, x) 在同一區,不能合併,回傳 False
        for x, y in self.restrict:
            root_x, root_y = self.rfind(x), self.rfind(y)
            if (root_u == root_x and root_v == root_y) or (root_u == root_y and root_v == root_x):
                return False
        # 不在限制條件中,可以合併
        return True

class Solution:
    def friendRequests(self, n: int, restrictions: list[list[int]], requests: list[list[int]]) -> list[bool]:
        dsu = DisjointSetUnion(n)
        
        # 於 dsu 之中加入所有的限制條件
        for u, v in restrictions:
            dsu.addRestrict(u, v)

        # 依序讀取 requests 的資料,先檢查 (u, v) 是否可以合併
        # 如果可以合併才執行 dsu.unite(u, v)
        ans = []
        for u, v in requests:
            if dsu.canMerge(u, v):
                dsu.unite(u, v)
                ans.append(True)
            else:
                ans.append(False)

        return ans


C++ 程式碼


Runtime: 119 ms, beats 59.43%. Memory: 28.92 MB, beats 28.93%.
class DisjointSetUnion {
private:
    int n;  // 節點數量
    vector<int> parent, sz;  // 根節點,區塊大小
    vector<vector<int>> restricts;  // 限制條件

public:
    DisjointSetUnion(int m) {
        n = m;
        parent.assign(n, 0);
        iota(parent.begin(), parent.end(), 0);
        sz.assign(n, 1);
        restricts.clear();
    }
    
    int rfind(int x) {  // 路徑壓縮,找根節點
        if (parent[x] == x) return x;

        parent[x] = rfind(parent[x]);
        return parent[x];
    }

    bool unite(int u, int v) {  // 合併區塊
        int root_u = rfind(u), root_v = rfind(v);
        if (root_u != root_v) {
            if (root_u > root_v) {
                swap(root_u, root_v);
            }
            sz[root_u] += sz[root_v];
            parent[root_v] = root_u;
            return true;
        }
        return false;
    }
    
    void addRestrict(int u, int v) {  // 加入限制條件
        restricts.push_back({u, v});
    }

    bool canMerge(int u, int v) {  // 檢查 u, v 是否可以合併
        int root_u = rfind(u), root_v = rfind(v);
        // u, v 已經在同一個區塊,回傳 true
        if (root_u == root_v) return true;

        // 依序檢查所有的限制條件,如果 (u, x) 在同一區且 (v, y) 在同一區,
        // 或是 (u, y) 在同一區且 (v, x) 在同一區,不能合併,回傳 False
        for(const auto& it :restricts) {
            int root_x = rfind(it[0]), root_y = rfind(it[1]);
            if ((root_u == root_x && root_v == root_y) || (root_u == root_y && root_v == root_x)) {
                return false;
            }
        }
        // 不在限制條件中,可以合併
        return true;
    }
};

class Solution {
public:
    vector<bool> friendRequests(int n, vector<vector<int>>& restrictions, vector<vector<int>>& requests) {
        DisjointSetUnion dsu (n);
        
        // 於 dsu 之中加入所有的限制條件
        for(const auto& it : restrictions) {
            dsu.addRestrict(it[0], it[1]);
        }

        // 依序讀取 requests 的資料,先檢查 (u, v) 是否可以合併
        // 如果可以合併才執行 dsu.unite(u, v)
        vector<bool> ans;
        for(const auto& it : requests) {
            if (dsu.canMerge(it[0], it[1])) {
                dsu.unite(it[0], it[1]);
                ans.push_back(true);
            } else {
                ans.push_back(false);
            }
        }
        return ans;
    }
};


沒有留言:

張貼留言