HDU 4857 逃生

来源:互联网 发布:阿里云上传视频教程 编辑:程序博客网 时间:2024/04/29 17:11

题目大意:中文

题目链接

注释代码:

/*                                  * Problem ID : HDU 4857 逃生 * Author     : Lirx.t.Una                                  * Language   : C++                      * Run Time   : 218 ms                                  * Run Memory : 1324 KB                                 */ #include <iostream>#include <cstring>#include <cstdio>#include <queue>#include <stack>//最大点数#defineMAXN30000//最大边数#defineMAXM1000000//由于点数太多使用邻接表存using namespace std;//由于输入保证有解因此无需判环//但是会有重边,因此算入读的时候会多算//但是在进行拓扑排序的时候也会多拆点//因此不影响最后结果inthead[MAXN + 1];intto[MAXM + 1];intnxt[MAXM + 1];inte;shortdeg[MAXN + 1];//入度,元素大小在MAXN范围内,用short保存//要求多解情况下先考虑最前面的号码最小,因此连边的时候反向连//拆点的时候从最大的拆stack<short>ans;//因此结果的顺序和实际顺序相反,用栈存以便按照正确顺序输出priority_queue<short>heap;//保存入度为0的点,让最大点排在堆顶voidaddarc( int u, int v ) {deg[v]++;to[e] = v;nxt[e]  = head[u];head[u] = e++;}voidtopsort(int n) {inti;intu;for ( i = 1; i <= n; i++ )if ( !deg[i] )heap.push(i);while ( !heap.empty() ) {ans.push(u = heap.top());heap.pop();for ( i = head[u]; i; i = nxt[i] )if ( !( --deg[ to[i] ] ) )heap.push( to[i] );}printf("%d", ans.top());ans.pop();while ( !ans.empty() ) {printf(" %d", ans.top());ans.pop();}putchar('\n');}intmain() {intt;intn, m;//点数,边数intu, v;scanf("%d", &t);while ( t-- ) {memset(head, 0, sizeof(head));scanf("%d%d", &n, &m);e = 1;while ( m-- ) {scanf("%d%d", &v, &u);addarc( u, v );//注意!!反向连边}topsort(n);}return 0;}
无注释代码:

#include <iostream>#include <cstring>#include <cstdio>#include <queue>#include <stack>#defineMAXN30000#defineMAXM1000000using namespace std;inthead[MAXN + 1];intto[MAXM + 1];intnxt[MAXM + 1];inte;shortdeg[MAXN + 1];stack<short>ans;priority_queue<short>heap;voidaddarc( int u, int v ) {deg[v]++;to[e] = v;nxt[e]  = head[u];head[u] = e++;}voidtopsort(int n) {inti;intu;for ( i = 1; i <= n; i++ )if ( !deg[i] )heap.push(i);while ( !heap.empty() ) {ans.push(u = heap.top());heap.pop();for ( i = head[u]; i; i = nxt[i] )if ( !( --deg[ to[i] ] ) )heap.push( to[i] );}printf("%d", ans.top());ans.pop();while ( !ans.empty() ) {printf(" %d", ans.top());ans.pop();}putchar('\n');}intmain() {intt;intn, m;intu, v;scanf("%d", &t);while ( t-- ) {memset(head, 0, sizeof(head));scanf("%d%d", &n, &m);e = 1;while ( m-- ) {scanf("%d%d", &v, &u);addarc( u, v );}topsort(n);}return 0;}

0 0
原创粉丝点击