题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1285
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#define MAXN 502
using namespace std;
vector<int>mp[MAXN];
int ans[MAXN],degree[MAXN],n;
struct cmp
{
bool operator ()(int x,int y)
{
return x>y;//小的优先级高
}
};
priority_queue<int,vector<int>,cmp>Q;//最小优先队列
void toposort()
{
int i,j,t,x,tot=0;
while(!Q.empty())
Q.pop();
memset(degree,0,sizeof(degree));
for(i=1;i<=n;++i)
{
for(j=0;j<mp[i].size();++j)
degree[mp[i][j]]++;
}
for(i=1;i<=n;++i)
{
if(!degree[i])
Q.push(i);//先把入度为0的点放入队列
}
while(!Q.empty())
{
x=Q.top();
Q.pop();
ans[tot++]=x;
for(j=0;j<mp[x].size();++j)
{
t=mp[x][j];
degree[t]--;
if(!degree[t])
Q.push(t);
}
}
}
int main()
{
int m,i,j;
while(scanf("%d %d",&n,&m)!=EOF)
{
memset(ans,0,sizeof(ans));
for(i=0;i<MAXN;++i)
mp[i].clear();
while(m--)
{
scanf("%d %d",&i,&j);
mp[i].push_back(j);//邻接表
}
toposort();
printf("%d",ans[0]);
for(i=1;i<n;++i)
printf(" %d",ans[i]);
printf("\n");
}
return 0;
}