【HDOJ】4857 逃生
很容易想到优先队列+拓扑排序。关键点是有限制条件者有限,无限制条件者在最后,条件相同者按序输出。因此采用逆序。
1 #include <iostream> 2 #include <queue> 3 #include <algorithm> 4 #include <cstdio> 5 #include <cstring> 6 using namespace std; 7 8 #define MAXN 30005 9 10 typedef struct { 11 int to, next; 12 } edge_st; 13 14 edge_st edges[100005]; 15 int adj[MAXN], L; 16 int deg[MAXN]; 17 int buf[MAXN]; 18 19 typedef struct node_st{ 20 int i; 21 node_st() {} 22 node_st(int ii) { 23 i = ii; 24 } 25 friend bool operator <(node_st a, node_st b) { 26 return a.i < b.i; 27 } 28 } node_st; 29 30 void add(int u, int v) { 31 edges[L].to = v; 32 edges[L].next = adj[u]; 33 adj[u] = L++; 34 ++deg[v]; 35 } 36 37 void init() { 38 L = 1; 39 memset(deg, 0, sizeof(deg)); 40 memset(adj, 0, sizeof(adj)); 41 } 42 43 int main() { 44 int T, n, m; 45 int i, j, k; 46 node_st nd; 47 48 scanf("%d", &T); 49 while (T--) { 50 scanf("%d%d", &n, &m); 51 init(); 52 while (m--) { 53 scanf("%d %d", &j, &k); 54 add(k, j); 55 } 56 priority_queue<node_st> Q; 57 for (i=1; i<=n; ++i) 58 if (deg[i] == 0) 59 Q.push(node_st(i)); 60 k = 0; 61 while (!Q.empty()) { 62 nd = Q.top(); 63 buf[k++] = nd.i; 64 Q.pop(); 65 for (i=adj[nd.i]; i; i=edges[i].next) { 66 deg[edges[i].to]--; 67 if (deg[edges[i].to] == 0) 68 Q.push(node_st(edges[i].to)); 69 } 70 } 71 for (i=k-1; i>=0; --i) 72 if (i) 73 printf("%d ", buf[i]); 74 else 75 printf("%d\n", buf[i]); 76 } 77 78 return 0; 79 }