您的位置:首页 > 其它

算法分析与设计课程作业第十周#1

2017-11-19 21:51 429 查看

算法分析与设计课程作业第十周#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
;
vector<int> topo;
int pre
;
int post
;
int time = 0;
bool found
;
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: