算法分析與設計課程作業第十週#1

算法分析與設計課程作業第十週#1

這周做了幾題,其中一題是圖論的題目。

210. Course Schedule II

There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]
4, [[1,0],[2,0],[3,1],[3,2]]
There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].
Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
You may assume that there are no duplicate edges in the input prerequisites.

思路

其實就是拓撲排序,深度優先搜索遍歷圖,然後將點按得到的post值從大到小排列就是其中一個拓撲排序的解。也可以在遍歷的過程中將節點入棧,遍歷完後將節點逐個出棧(實現逆轉順序的效果)得到的結果也爲所求。
按從大到小

代碼

#include <vector>
#include <algorithm>
#include<utility>  
using namespace std;
class Solution {
public:
    void traverse(vector<int> edge[], int vertice, bool found[], vector<int>& topo,int pre[], int post[], int& time){
        ++time;
        pre[vertice] = time;
        found[vertice] = true;
        vector<int> ::iterator iter;
        for(iter = edge[vertice].begin(); iter != edge[vertice].end(); iter++){
            if(!found[*iter]){
                traverse(edge, *iter, found, topo, pre, post, time);
            }
        }
        ++time;
        post[vertice] = time;
        topo.push_back(vertice);
    }
    vector<int> findOrder(int n, vector<pair<int, int>>& edges) {
        vector<int> edge[n];
        vector<int> topo;
        int pre[n];
        int post[n];
        int time = 0;
        bool found[n];
        for(int j = 0; j < n; j++){
            found[j] = false;
        }
        vector<pair<int, int>> ::iterator i = edges.begin();
        for( ; i != edges.end(); i++){
            edge[i->second].push_back(i->first);
        }
        for(int j = 0; j < n; j++){
            if(!found[j]){
                traverse(edge, j, found, topo, pre, post, time);
            }
        }
        vector<int> zero;
        for(int j = 0; j < n; j++){
            vector<int> ::iterator iter;
            for(iter = edge[j].begin(); iter != edge[j].end(); iter++){
                if(pre[*iter] <= pre[j] && post[j] <= post[*iter]) return zero;
            }
        }
        reverse(topo.begin(), topo.end());
        return topo;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章