hdu 4857 逆向拓扑排序+反向输出

/*一组测试实例
4 
4 2
3 1
2 4
*/
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
#define N 31000
struct node {
int u,v,next;
}bian[N*10];
int head[N],yong,indegree[N],n,f[N],len;
void init() {
memset(head,-1,sizeof(head));
yong=0;
memset(indegree,0,sizeof(indegree));
}
void addedge(int u,int v) {
bian[yong].u=u;
bian[yong].v=v;
bian[yong].next=head[u];
head[u]=yong++;
}
void bfs() {
    priority_queue<int>q;
   int i,cur;
   for(i=1;i<=n;i++)
    if(indegree[i]==0)
    q.push(i);
   while(!q.empty()) {
    cur=q.top();
    q.pop();
    f[len++]=cur;
    for(i=head[cur];i!=-1;i=bian[i].next) {
        int v=bian[i].v;
        if(--indegree[v]==0)
            q.push(v);
    }
   }
   return ;
}
int main(){
   int t,m,i,j;
   scanf("%d",&t);
   while(t--) {
        init();
    scanf("%d%d",&n,&m);
    while(m--) {
        scanf("%d%d",&i,&j);
        indegree[i]++;
        addedge(j,i);
    }
    len=0;
    bfs();
    for(i=len-1;i>=1;i--)
        printf("%d ",f[i]);
    printf("%d\n",f[i]);
   }
return 0;
}

posted @ 2014-07-21 17:18  HYDhyd  阅读(160)  评论(0编辑  收藏  举报