Problem:
在图论中,拓扑序(Topological Sorting)是一个有向无环图(DAG, Directed Acyclic Graph)的所有顶点的线性序列. 且该序列必须满足下面两个条件:
1.
每个顶点出现且只出现一次.
2.
若存在一条从顶点 A 到顶点 B 的路径,那么在序列中顶点 A 出现在顶点 B 的前面.
对于一个含有n个节点的有向无环图(节点编号0到n-1),输出它的一个拓扑序.
图的节点数和边数均不多于100000,保证输入的图是一个无环图.
请为下面的Solution类实现解决上述问题的topologicalSort函数,函数参数中n为图的节点数,edges是边集,edges[i]表示第i条边从edges[i].first指向edges[i].second. 函数返回值为有向图的一个拓扑序. 有向图有多个拓扑序时,输出任意一个即可.
class Solution {
public:
vector<int> topologicalSort(int n, vector<pair<int, int>>& edges) {
}
};
例1:
n = 3,edges = {(0, 1), (0, 2)},函数应返回{0, 1, 2}或者{0, 2, 1}.
例2:
n = 4,edges = {(0, 1), (0, 2), (1, 2), (3, 0)},函数应返回{3, 0, 1, 2}.
注意:你只需要提交Solution类的代码,你在本地可以编写main函数测试程序,但不需要提交main函数的代码. 注意不要修改类和函数的名称.
Solution:
// Problem#: 21104 // Submission#: 5252736 // The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License // URI: http://creativecommons.org/licenses/by-nc-sa/3.0/ // All Copyright reserved by Informatic Lab of Sun Yat-sen University #include<algorithm> #include<stdio.h> #include<iostream> #include<cstring> #include<stdlib.h> #include<vector> using namespace std; class Solution { private: vector< vector<int> > V; vector<int> ans; vector<bool> vis; void dfs(int n) { int v, i; vis[n] = true; for (i = 0; i<V[n].size(); i++) { v = V[n][i]; if (!vis[v]) dfs(v); } ans.push_back(n); } public: vector<int> topologicalSort(int n, vector< pair<int, int> >& edges) { int u, v, i; V.resize(n); vis.resize(n); for (i = 0; i<edges.size(); i++) { u = edges[i].first; v = edges[i].second; V[v].push_back(u); }//V[v]代表有那些点能够达到v; for (i = 0; i<n; i++) vis[i] = false;//初始化bool值 for (i = 0; i<n; i++) if (!vis[i]) dfs(i); return ans; } };