http://acm.hdu.edu.cn/showproblem.php?pid=1285
拓扑排序,邻接矩阵存储,注意重边
#include <stdio.h>
#include <string.h>
int adjMatrix[501][501],indegree[501];
int n,m;
void initTopo()
{
int p1,p2;
memset(indegree,0,sizeof(indegree));
memset(adjMatrix,0,sizeof(adjMatrix));
while(m--)
{
scanf("%d %d",&p1,&p2);
if(adjMatrix[p1][p2]==0)
{
adjMatrix[p1][p2]=1;
indegree[p2]++;
}
}
}
void topoSort()
{
int i,j,count=0;
while(count<n)
{
for(i=1;i<=n;i++)
if(indegree[i]==0)
{
indegree[i]=-1;
break;
}
if(count>0)
printf(" ");
printf("%d",i);
count++;
for(j=1;j<=n;j++)
if(adjMatrix[i][j])
indegree[j]--;
}
printf("\n");
}
int main()
{
while(~scanf("%d %d",&n,&m))
{
initTopo();
topoSort();
}
return 0;
}