Chinaunix首页 | 论坛 | 博客
  • 博客访问: 38569
  • 博文数量: 64
  • 博客积分: 2640
  • 博客等级: 少校
  • 技术积分: 670
  • 用 户 组: 普通用户
  • 注册时间: 2010-01-26 13:15
文章分类
文章存档

2010年(64)

我的朋友
最近访客

分类: C/C++

2010-01-26 13:41:51

2008-10-31 20:19

#include<iostream>
using namespace std;
const int INC = 20;
class Stack{
      public:
      Stack(){ st = new int[INC]; top = -1; }
      Stack(int i);
      void Push(int i);
      void Pop(int& i);
      bool IsEmpty(){ return top==-1; }
      private:
      int* st;
      int top;
      int max_size;
};
bool adjmat[10][10] = {0};
int vexnum = 6,vexinfo[10];
bool TopologicalSort();
int main(void){
    adjmat[0][1] = 1;
    adjmat[0][2] = 1;
    adjmat[0][3] = 1;
    adjmat[2][1] = 1;
    adjmat[3][4] = 1;
    adjmat[2][4] = 1;
    adjmat[5][3] = 1;
    adjmat[5][4] = 1;
   
    cout<<"Input vexinfo:";
    for(int i=0;i<vexnum;i++)
        cin>>vexinfo[i];
       
    if(TopologicalSort())
       cout<<"No cycle";
    else cout<<"Cycle exists!";
    cout<<endl;
   
    system("pause");
    return 0;
}
Stack::Stack(int i){
     st = new int[i+INC];
     top = -1;
     max_size = i+INC;
}
void Stack::Push(int i){
     if(top+1>=max_size){
        cout<<"Stack full!"<<endl;
        system("pause");
        exit(0);
     }
     st[++top] = i;
}
       
void Stack::Pop(int& i){
     if(IsEmpty()){
        cout<<"Stack empty!"<<endl;
        system("pause");
        exit(0);
     }
     i = st[top];
     top--;
}
bool TopologicalSort(){
     int indeg[10];
     int i,j,count=0;
     Stack stc(vexnum);
     memset(indeg,0,sizeof(indeg));
    
     for(i=0;i<vexnum;i++)
         for(j=0;j<vexnum;j++)
             if(adjmat[j][i]) indeg[i]++;
    
     for(i=0;i<vexnum;i++)
         if(!indeg[i]) stc.Push(i);
    
     while(!stc.IsEmpty()){
           stc.Pop(i);
           cout<<i+1<<" "<<vexinfo[i]<<endl;
           count++;
           for(j=0;j<vexnum;j++)
               if(adjmat[i][j])
                  if(--indeg[j]==0) stc.Push(j);
     }
     cout<<endl;
    
     if(count==vexnum) return true;
     else return false;
}


阅读(163) | 评论(0) | 转发(0) |
0

上一篇:对AOE网求关键路径

下一篇:BST的逐层遍历

给主人留下些什么吧!~~