HDU 1285

//典型的拓扑排序算法(邻接阵形式),可以作为拓扑排序的模板
#include <iostream>
//#include <conio.h>
using namespace std;
#define arraysize 501
int map[arraysize][arraysize];   //存储图的临界阵
int n,m;
int indegree[arraysize];    //存储点的入度
int main()
{
    int i,j,k;
    int p1,p2;
    //freopen("1.txt","r",stdin);
    while(cin>>n>>m)
    {
        memset(map,0,sizeof(map));
        memset(indegree,0,sizeof(indegree));
        for(i=0;i<m;++i)
        {
            cin>>p1>>p2;
            if(!map[p1][p2])     //此处别忘了重边的判断,否则会wa
            {
                map[p1][p2] =1;
                indegree[p2]++;           
            }           
        }
        //拓扑排序
        for(i=1;i<n+1;++i)      //进行n次遍历,每次找出一个入度为0的节点             
        {
            for(j=1;j<n+1;++j)  //遍历所有节点 
            {
                if(indegree[j]==0)    //找出入度为0的节点
                {
                    indegree[j]--;    //度数递减,避免下次继续找到
                    if(i!=n)
                    {
                       cout<<j<<" ";
                    }
                    else
                       cout<<j<<endl;
                    for(k=1;k<n+1;++k)
                    {
                        if(map[j][k]==1)   // 删除与度数为0的节点相关联的边
                        {
                            indegree[k]--;
                        }
                    }
                    break;
                }                            
            }
        }
    }
    //getch();
    return 0;
}

你可能感兴趣的:(HDU)