拓扑排序(c++)
伪码
pricedure to pological sort(S:有穷偏序集合)
while !S.empty()
begin
curr = 入度为0点
S = S - {curr}
end
C++代码
#include <bits/stdc++.h>
using namespace std;
//入度为0的点就是没有任何以他为起点的点
int main()
{
int n, m;
cin >> n >> m; // n个点,m条边
vector<int> indegree(n + 1); //点的入度
vector<pair<int, int>> Edge;
vector<int> topo(n + 1);
for (int i = 0; i < m; i++)
{
int x, y;
cin >> x >> y;
Edge.push_back(make_pair(x, y)); // x==起点,y=终点
indegree[y]++;
}
queue<int> q; //找到入度最小的点
q.push(1);
topo[1] = 1;
while (!q.empty())
{
int curr = q.front();
q.pop();
for (auto e : Edge)
{
if (e.first == curr) //寻找该点的下一条边所对应的点
{
indegree[e.second]--; //该点入度减少
if (indegree[e.second] == 0)
{
topo[e.second] = topo[curr] + 1;
q.push(e.second);
}
}
}
}
for (int i = 1; i <= n; i++)
cout << topo[i] << endl;
}

浙公网安备 33010602011771号