#include<iostream>
#include<vector>
#include<list>
#include<queue>
using namespace std;
class Graph
{
public:
std::vector<list<int> > neighbour;
std::vector<int> indegree;
int verNum;
int arcNum;
};
Graph makegraph()
{
Graph g;
cin>>g.verNum;
cin>>g.arcNum;
g.neighbour.resize(g.verNum+1);
g.indegree.resize(g.arcNum+1);
int v,m;
for (int i = 0; i < g.arcNum; ++i)
{
/* code */
cin>>v>>m;
g.neighbour[v].push_back(m);//for list , add a elem, is push or push_back()?
g.indegree[m]++;
}
return g;
}
vector<int> topologicalSorting(Graph g)
{
priority_queue <int, std::vector<int>, greater<int> >q;
vector<int> ordering;
for (int i = 1; i <= g.verNum; ++i)
{
/* code */
if(g.indegree[i]==0)
q.push(i);
}
while(!q.empty())
{
int v=q.top();
q.pop();
ordering.push_back(v);
list<int>::iterator it=g.neighbour[v].begin();
while(it!=g.neighbour[v].end())
{
g.indegree[*(it)]--;
if(g.indegree[*it]==0)
q.push(*it);
it++;
//priority_queue<int, std::vector<int, std::allocator<int> >, std::greater<int> >' has no member named 'push_back'
}
}
return ordering;
}
int main()
{
Graph graph=makegraph();
std::vector<int> v=topologicalSorting(graph);
for (int i = 0; i < v.size(); ++i)
{
/* code */
cout<<v[i]<<" ";
}
cout<<endl;
system("pause");
return 0;
}
/*
5 5
3 4
4 1
3 2
2 4
5 3
*/
拓扑排序
最新推荐文章于 2025-05-13 21:35:52 发布