hdu-4857-Escape-Reverse topology sort + Priority queue

Source: Internet
Author: User

HDU-4857

Test instructions is to do a qualifying sort, using the topological sequence.

I started with a lot of WA, only to find that there are a few examples too, found 1->2->3 ... the order is not guaranteed.

Later I wanted to use and check the strong company, or WA;

Later found that the use of reverse topology sorting + priority queue to pass;

Notice here that the entry to the 0 is changed into a 0-degree queue

Here is the AC code:

#include <cstring>#include<queue>#include<cstdio>using namespaceStd;vector<int>to[30000+Ten];intn,m,cnt;intoutdeed[30000+Ten],topo [30000+Ten];voidinit () {memset (outdeed,0,sizeof(outdeed));  for(intI=1; i<=n;i++) to[i].clear (); memset (topo,0,sizeof(topo));}voidToposort () {priority_queue<int>Q;  for(intI=1; i<=n;i++)        if(!Outdeed[i]) Q.push (i); CNT=0;  while(!Q.empty ()) {        intTMP =Q.top ();        Q.pop (); topo[++cnt]=tmp; intK =to[tmp].size ();  for(intI=0; i<k;i++)        {            inttt =To[tmp][i]; OUTDEED[TT]--; if(outdeed[tt]==0) Q.push (TT); }    }}voidoutput () { for(inti=n;i>=1; i--) printf ("%d%c", topo[i],i==1?'\ n':' ');}intMain () {intT; scanf ("%d",&T);  while(t--) {scanf ("%d%d",&n,&m);        Init ();  for(intI=1; i<=m;i++)        {            intu,v; scanf ("%d%d",&u,&v);            To[v].push_back (U); Outdeed[u]++;        } toposort ();    Output (); }    return 0;}

hdu-4857-Escape-Reverse topology sort + Priority queue

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.