// 拓撲#include<iostream>#include<queue>#include<vector>usingnamespace std;constint MAX =100000;// 鄰接點
vector<vector<int>> outdegree;// 每個點的入度
vector<int> Indegree;int N;
vector<int> TopOder;boolTopSort(){
queue<int> q;// 初始化隊列// 初始入度爲0 加入初始隊列for(int i =1; i <= N; i++){if(Indegree[i]==0)
q.push(i);}// 進入拓撲排序int cnt =0;// 結果while(!q.empty()){// 每次拿出入度爲0的結點int V = q.front();
q.pop();
cnt++;
TopOder.push_back(V);// 看入度爲0的結點的下一個結點// 下一個結點如果減去入度爲的結點// 然後入度也爲0的話 就再加到隊列for(auto e : outdegree[V]){if(--Indegree[e]==0)
q.push(e);}}for(auto e : TopOder)
cout << e <<' ';
cout << endl;// 有循環圖的話cnt是不等於N的return cnt == N ?true:false;}int visited[MAX];voiddfs(int v){
visited[v]=1;for(auto e : outdegree[v]){if(!visited[e]){dfs(e);}}
TopOder.push_back(v);}intmain(){int M;
cin >> N >> M;
outdegree.resize(N +5);
Indegree.resize(N +5);for(int i =0; i < M; i++){int x, y;
cin >> x >> y;// 記錄入度
Indegree[y]++;
outdegree[x].push_back(y);}
cout << endl
<<TopSort();return0;}
2. 鄰接矩陣 + 棧 + BFS
鄰接矩陣 + 棧
/ 鄰接矩陣法
// #include <iostream>// #include <stack>// using namespace std;// const int MAX = 1000;// int out[MAX][MAX];// int Indegree[MAX];// int N;// bool topological()// {// // 記錄入度// for (int i = 1; i <= N; i++)// {// for (int j = 1; j <= N; j++)// {// if (out[i][j] == 1)// {// ++Indegree[j];// }// }// }// stack<int> s;// for (int i = 1; i <= N; i++)// {// if (Indegree[i] == 0)// s.push(i);// }// int TopOder[MAX];// int cnt = 0;// while (!s.empty())// {// int x = s.top();// s.pop();// TopOder[++cnt] = x;// for (int i = 1; i <= N; i++)// {// if (out[x][i] == 1)// {// if (--Indegree[i] == 0)// {// s.push(i);// }// }// }// }// }// int main()// {// return 0;// }