[HDU] [4857] Escape

Problem Description

Loading...

Problem Analysis

This is clearly a topological sort, but this problem has two conditions: in addition to the given constraints, the output should preferably follow the order from 1 to n.

So consider using a priority queue to pick suitable vertices.

Consider that earlier elements should be as large as possible compared with later ones. Therefore, if a priority queue is used and edges are built in the forward direction, an element from the previous layer already in the queue may be larger than a later-pushed element, causing the queue to output strictly in descending order and producing an incorrect result.

So consider building edges in reverse. Then first take the largest among the smallest level, and each time take the largest element in the current queue. This guarantees sorting according to the special condition while following the order from 1 to n.

Because the edges are built in reverse, the obtained result must be output in reverse order.

Test data:

1
2
3
4
5
6
10  
6 4  
6 3  
3 1  
5 4  
4 2  

Output:

1
6 3 1 5 4 2
cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int n;
int cnt[30200];
int topo[30200];
struct node {
	int next;
	int to;
} a[100200];
int head[30200];
void toposort() {
	priority_queue<int>q;
	for(int i=1; i<=n; i++)
		if(!cnt[i]) {
			q.push(i);
		}
	int t=0;
	while(!q.empty()) {
		int ttop=q.top();
		q.pop();
		topo[t++]=ttop;
		for(int i=head[ttop]; i!=-1; i=a[i].next) {
			cnt[a[i].to]--;
			if(!cnt[a[i].to])
				q.push(a[i].to);
		}
	}
}
int main() {
	int T;
	scanf("%d",&T);
	while(T--) {
		int m;
		scanf("%d %d",&n,&m);
		memset(cnt,0,sizeof(cnt));
		memset(head,-1,sizeof(head));
		for(int i=0; i<m; i++) {
			int u,v;
			scanf("%d %d",&u,&v);
			a[i].to=u;
			a[i].next=head[v];
			head[v]=i;
			cnt[u]++;
		}
		toposort();
		for(int i=n-1; i>=0; i--)
			printf("%d%c",topo[i],i==0?'\n':' ');
	}
	return 0;
}

Loading...