【第27場雙週賽】Leetcode-1462. 課程安排 IV

有一說一,這周兩道圖雙雙超時真的讓我傷心眼淚流,流淚貓貓頭。
究竟是鄰接表還是鄰接矩陣呢?

Floyed

本題類似於Leetcode-399 除法求值,所以也可以考慮並查集算法,但是還是floyed簡單。
floyed算法可求出多源最短路徑,本題只需求是否有路徑。
選取每一個點爲中轉點k,獲取圖中任意兩點的關係。

class Solution {
public:
    vector<bool> checkIfPrerequisite(int n, vector<vector<int>>& prerequisites, vector<vector<int>>& queries) {
            vector<vector<bool>> graph(n,vector<bool>(n,false));
            vector<bool> res;
            for(int i=0;i<prerequisites.size();i++)
            {
                int oldclass=prerequisites[i][0];
                int newclass=prerequisites[i][1];
                graph[oldclass][newclass]=true;
            }
            for(int k=0;k<n;k++)
                for(int i=0;i<n;i++)
                    for(int j=0;j<n;j++)
                    {
                        if(graph[i][j]==false)
                            graph[i][j]=graph[i][k]&&graph[k][j];
                    }
            for(int i=0;i<queries.size();i++)
            {
                int oldclass=queries[i][0];
                int newclass=queries[i][1];
                if(graph[oldclass][newclass])
                    res.push_back(true);
                else
                    res.push_back(false);
            }
        return res;
    }
};

自我經驗總結

感覺都不好意思再寫一個題解,明明題目很簡單,就一個事! Floyed它不香嘛!
在超時的錯誤解法中,我用了鄰接表,然後對於每一段新加入的關係都去遍歷一個數組,導致效率很糟糕,但是事實上圖的關係並不稀疏,完全不如floyed簡單輕鬆。
圖的算法還是要多做一些!

//對於讀入新關係後的處理
     graph[newclass].push_back(oldclass);
     for(int j=0;j<graph[oldclass].size();j++)
        graph[newclass].push_back(graph[oldclass][j]);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章