#include<iostream>
#include<vector>
#include<list>
#include<queue>
#include<algorithm>
using namespace std;
class vertex{
public:
int indegree;
vector<vertex*> next;
// List<int> adj;
int topnum;
int f;
vertex():indegree(0),topnum(0){}
};
bool mycomp( const vertex & v1,const vertex &v2)
{
if(v1.topnum!=v2.topnum)return v1.topnum<v2.topnum;
else
return v1.topnum<v2.topnum;
}
int main()
{
vector<vertex>graph;
vector<vertex>out;
vertex v1,v2,v3,v4,v5,v6,v7;
v1.next.push_back(&v2);
v2.indegree++;
v1.next.push_back(&v3);
v3.indegree++;
v1.next.push_back(&v4);
v4.indegree++;
v2.next.push_back(&v4);
v4.indegree++;
v2.next.push_back(&v5);
v5.indegree++;
v3.next.push_back(&v6);
v6.indegree++;
v4.next.push__back(&v6);
v6.indegree++;
v5.next.push_back(&v4);
v4.indegree++;
v5.next.push_back(&v7);
v7.indegree++;
v7.next.push_back(&v6);
v6.indegree++;
v1.f=1;
v2.f=2;
v3.f=3;
v4.f=4;
v5.f=5;
v6.f=6;
v7.f=7;
graph.push_back(v1);
graph.push_back(v2);
graph.push_back(v3);
graph.push_back(v4);
graph.push_back(v5);
graph.push_back(v6);
graph.push_back(v7);
queue<vertex> q;
int count=0;
vector<vertex>::iterator it;
for(it=graph.begin();it!=graph.end();it++)
{
if(it->indegree==0)
q.push(*it);
}
while(q.size()!=0)
{
vertex v=q.front();
q.pop();
v.topnum=++count;
out.push_back(v);
vector<vertex*>::iterator it2;
for(it2=v.next.begin();it2!=v.next.end();it2++)
if((--((*it2)->indegree))==0) q.push(**it2);
}
sort(out.begin(),out.end(),mycomp);
for(it=out.begin();it!=out.end();it++)
cout<<"v"<<it->f<<endl;
return 0;
}
拓扑排序
最新推荐文章于 2025-05-13 21:35:52 发布