Excerpt from: http://blog.csdn.net/lansetiankong_yiyi/article/details/5815097
#include<iostream>
#define MAX 501using namespacestd;inttopo[501];intgraph[501][501];intb;intn,m;intToposort (intNintMAT[][MAXN],int* ret)//N is the number of points, Mat is the adjacency matrix, ret is the sorted point column{ intD[maxn],i,j,k;//d Array records the number of degrees per point for(i=0; i<n;i++) for(d[i]=j=0; j<n;d[i]+=mat[j++][i]);//This is the calculation of the in degrees of each point. for(k=0; k<n;ret[k++]=i) { for(i=0;d [i]&&i<n;i++];//here is the point of looking into the degree of 0 if(i==N)return 0; for(d[i]=-1, j=0; j<n;j++) D[j]-=MAT[I][J];//in degrees to be reduced by one } return 1;}intMain () { while(cin>>n>>m) {memset (graph,0,sizeofgraph); for(intI=1; i<=m;i++) {cin>>a>>C; Graph[a-1][b-1]=1; } toposort (N,graph,topo); for(intI=0; i<n;i++) { if(i) cout<<' '; cout<<topo[i]+1; } cout<<Endl; }}
Topology Sorting (templates)