转自于http://www.cnblogs.com/longdouhzt/archive/2011/08/05/2128996.html
#include<iostream>
#include<stack>
using namespace std;
const int maxV=100,white=0,gray=1,black=2;
int v,itime;
struct SNode{//节点
int color,d,f,num;
SNode *p;
};
struct SAdj{//邻接表
int num;
SAdj *next;
};
SAdj *adj[maxV];
SNode *vertex[maxV];
stack<SNode*> vertexStack;
//初始化
void init(){
for(int i=1;i<=v;i++){
adj[i]=new SAdj;
adj[i]->next=NULL;
}
for(int i=1;i<=v;i++){
vertex[i]=new SNode;
vertex[i]->color = white;
vertex[i]->p=NULL;
vertex[i]->num = i;
}
itime=0;
}
void dfs(){
SNode *top;
for(int i=1;i<=v;i++){
if(vertex[i]->color==white){
vertex[i]->color=gray;
vertex[i]->d=++itime;
vertex[i]->p=NULL;
vertexStack.push(vertex[i]);
}
while(!vertexStack.empty()){
top=vertexStack.top();
SAdj *cur=adj[top->num];
while(cur->next!=NULL){
if(vertex[cur->next->num]->color==white){
vertex[cur->next->num]->color=gray;
vertex[cur->next->num]->d=++itime;
vertex[i]->p=top;
vertexStack.push(vertex[cur->next->num]);
top=vertexStack.top();
cur=adj[cur->next->num];
}
else
cur=cur->next;
}
top->F3_120M_512=++itime;
top->color=black;
vertexStack.pop();
}
}
}
void print(){
for(int i=1;i<=v;i++)
cout<<i<<" "<<vertex[i]->d<<" "<<vertex[i]->f<<endl;
}
int main(){
cin>>v;
init();
int tmpU,tmpV;
while(true){
cin>>tmpU>>tmpV;
if(tmpU==0) break;
SAdj *newNode=new SAdj;
newNode->num=tmpV;
newNode->next=adj[tmpU]->next;
adj[tmpU]->next=newNode;
}
dfs();
print();
return 0;
}
测试数据:
6
1 4
1 2
2 5
3 6
3 5
4 2
5 4
6 6
0 0
(书 P331)