BZOJ 4010 HNOI2015 dish production Topology Sorting + heap, bzojhnoi2015
Given an undirected graph, find a topological order so that:
1 is at the top
Make sure that 2 is at the top of the list under the above conditions.
Make sure that the top 3 position is the top 3 under the above conditions.
......
Note that it is not the smallest Lexicographic Order! Example 3
Create a reverse graph, find the largest topological order of the Lexicographic Order of the reverse graph, and then output it in reverse order.
I don't know why. I really don't know.
Online answers.
#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#define M 100100using namespace std;struct abcd{ int to,next;}table[M];int head[M],tot;int n,m;int degree[M];int stack[M],top;void Add(int x,int y){ table[++tot].to=y; table[tot].next=head[x]; head[x]=tot;}void Initialize(){ memset(head,0,sizeof head); tot=1; memset(degree,0,sizeof degree);}namespace Priority_Queue{ int heap[M],top; void Insert(int x) { heap[++top]=x; int t=top; while(t>1) { if(heap[t]>heap[t>>1]) swap(heap[t],heap[t>>1]),t>>=1; else break; } } void Pop() { heap[1]=heap[top--]; int t=2; while(t<=top) { if( t<top && heap[t+1]>heap[t] ) ++t; if(heap[t]>heap[t>>1]) swap(heap[t],heap[t>>1]),t<<=1; else break; } }}void Topology_Sort(){ using namespace Priority_Queue; int i; for(i=1;i<=n;i++) if(!degree[i]) Insert(i); while(Priority_Queue::top) { int x=heap[1];Pop(); stack[++::top]=x; for(i=head[x];i;i=table[i].next) if(!--degree[table[i].to]) Insert(table[i].to); }}int main(){ int T,i,x,y; for(cin>>T;T;T--) { Initialize(); scanf("%d%d",&n,&m); for(i=1;i<=m;i++) { scanf("%d%d",&x,&y); Add(y,x); degree[x]++; } top=0; Topology_Sort(); if(top!=n) puts("Impossible!"); else { for(i=n;i;i--) printf("%d ",stack[i],i==1?'\n':' '); puts(""); } } return 0;}