Topological sort Template Questions
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace Std;
const int MAXE=250000+10;
const int MAXH=500+10;
typedef struct EDGE
{
int to,next;
};
Edge E[maxe];
int head[maxh],in[maxh],n,m,cnt;
BOOL Map[maxh][maxh];
void init (int num)
{
for (int i=0;i<=num;i++)
{
Head[i]=-1;
in[i]=0;
for (int j=0;j<=num;j++)
Map[i][j]=false;
}
cnt=0;
}
void Add (int a,int b)
{
E[cnt].to=b;
E[cnt].next=head[a];
head[a]=cnt++;
}
int main ()
{
int x,y,sum;
while (~SCANF ("%d%d", &n,&m))
{
Init (n);
for (int i=0;i<m;i++)
{
scanf ("%d%d", &x,&y);
if (!map[x][y])
{
Map[x][y]=true;
Add (x, y);
in[y]++;
}
}
Priority_queue<int,vector<int>,greater<int> >Q;
for (int i=1;i<=n;i++)
{
if (!in[i])
{
Q.push (i);
}
}
Sum=n;
while (! Q.empty ())
{
int Fir=q.top ();
sum--;
Q.pop ();
if (sum) printf ("%d", fir);
else printf ("%d\n", fir);
for (int i=head[fir];i+1;i=e[i].next)
{
in[e[i].to]--;
if (!in[e[i].to])
{
Q.push (e[i].to);
}
}
}
}
return 0;
}
HDU 1285 Tournament Rankings "topological sorting"