Topic: Given an no-map, to find a topological order, so that:
Top 1 of the position
Make the top of the 2 position under the above conditions
Make the top of the 3 position under the above conditions
......
Note that it is not the smallest dictionary order! Sample 3, for example
The inverse graph is set up, the topological sequence of the dictionary order is obtained, and then the output is reversed.
I don't know why. Really don't know.
Ask for an answer online and so on.
#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#define M 100100using namespace STD;structabcd{intTo,next;} TABLE[M];intHead[m],tot;intN,m;intDEGREE[M];int Stack[M],top;voidADD (intXintY) {table[++tot].to=y; TABLE[TOT].NEXT=HEAD[X]; Head[x]=tot;}voidInitialize () {memset(Head,0,sizeofHead); tot=1;memset(Degree,0,sizeofdegree);}namespacepriority_queue{intHeap[m],top;voidInsert (intx) {heap[++top]=x;intT=top; while(t>1) {if(heap[t]>heap[t>>1]) Swap (heap[t],heap[t>>1]), t>>=1;Else Break; } }voidPop () {heap[1]=heap[top--];intt=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; } }}voidTopology_sort () {using namespacePriority_queue;intI for(i=1; i<=n;i++)if(!degree[i]) Insert (i); while(Priority_queue::top) {intx=heap[1]; Pop ();Stack[++::top]=x; for(I=head[x];i;i=table[i].next)if(!--degree[table[i].to]) Insert (table[i].to); }}intMain () {intT,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;}
Bzoj 4010 HNOI2015 Dishes making topological sort + heap