Description
Input
Output
Sample Input
1 5 10 3 5 1 4 2 5 1 2 3 4 1 4 2 3 1 5 3 5 1 2
AC代码
1 2 3 4 5
要用反向拓扑,例如4个人,3必须在1前面,2必须在4前面,首先想到的是用优先队列,从小到大排,但是这样的话2会排在1前面,但是题目要求要尽可能的让小的排在前面,所以反向拓扑,优先队列,从大到小,然后再放入栈中
#include<stdio.h>
#include<string.h>
#include<queue>
#include<stack>
using namespace std;
int n,m;
struct node{
int to,next;
}num[100010];
int head[30030];
int in[30010];
void topo()
{
priority_queue<int>q;
stack<int>s;
int i,j,top,t;
for(i=1;i<=n;i++)
if(in[i]==0)
q.push(i);
while(!q.empty())
{
top=q.top();
q.pop();
s.push(top);
for(i=head[top];i!=-1;i=num[i].next)
{
in[num[i].to]--;
if(in[num[i].to]==0)
q.push(num[i].to);
}
}
while(s.size()>1)
{
printf("%d ",s.top());
s.pop();
}
printf("%d\n",s.top());
}
int main()
{
int t,a,b,i;
scanf("%d",&t);
while(t--)
{
memset(head,-1,sizeof(head));
memset(in,0,sizeof(in));
scanf("%d%d",&n,&m);
for(i=0;i<m;i++)
{
scanf("%d%d",&a,&b);
num[i].to=a;
num[i].next=head[b];
head[b]=i;
in[a]++;
}
topo();
}
return 0;
}
topo
原文:http://www.cnblogs.com/ruruozhenhao/p/7663084.html