Topological Sort

#include<iostream>
#include<vector>
#include<string>
using namespace std;
class Node
{
public:
	Node(string data)
	{
		this->data=data;
		begin=0;
		finish=0;
		color="white";
		p=NULL;
	}
	string data;
	int begin;
	int finish;
	string color;
	Node *p;
	vector<Node*> vecAdj;
};
int time=0;
void DFS(vector<Node*> vecQ,Node *u);
void main()
{
	Node *jacket=new Node("jacket");
	Node *undershorts=new Node("undershorts");
	Node *pants=new Node("pants");
	Node *belt=new Node("belt");
	Node *socks=new Node("socks");
	Node *shoes=new Node("shoes");
	Node *shirt=new Node("shirt");
	Node *tie=new Node("tie");
	undershorts->vecAdj.push_back(pants);undershorts->vecAdj.push_back(shoes);
	pants->vecAdj.push_back(belt);pants->vecAdj.push_back(shoes);
	belt->vecAdj.push_back(jacket);
	socks->vecAdj.push_back(shoes);
	shirt->vecAdj.push_back(belt);shirt->vecAdj.push_back(tie);
	tie->vecAdj.push_back(jacket);
	vector<Node*> vecQ;
	vecQ.push_back(jacket);
	vecQ.push_back(undershorts);
	vecQ.push_back(pants);
	vecQ.push_back(belt);
	vecQ.push_back(socks);
	vecQ.push_back(shoes);
	vecQ.push_back(shirt);
	vecQ.push_back(tie);
	//kaishiole 
	for(vector<Node*>::iterator it=vecQ.begin();it<vecQ.end();it++)
	{
		if( (*it)->color=="white")
		DFS(vecQ,(*it));
	}
	Node *bit=shoes;
	bit=belt;
	while( bit != NULL )
	{
		cout<<bit->data<<" ";
		bit=bit->p;
	}
	cout<<endl;
	system("pause");
	//根据finish排序,就是拓扑排序
}
void DFS(vector<Node*> vecQ,Node *u)
{
	u->color="gray";
	time++;
	u->begin=time;
	for(vector<Node*>::iterator ict=u->vecAdj.begin();ict<u->vecAdj.end();ict++)
	{
		if( (*ict)->color == "white" )
		{
			(*ict)->p=u;
			DFS( vecQ,(*ict) );
		}
	}
	u->color="black";
	time++;
	u->finish=time;
}

你可能感兴趣的:(Topological Sort)