题目连接
http://acm.hdu.edu.cn/showproblem.php?pid=4857
逃生
Description
糟糕的事情发生啦,现在大家都忙着逃命。但是逃命的通道很窄,大家只能排成一行。
现在有n个人,从1标号到n。同时有一些奇怪的约束条件,每个都形如:a必须在b之前。
同时,社会是不平等的,这些人有的穷有的富。1号最富,2号第二富,以此类推。有钱人就贿赂负责人,所以他们有一些好处。
负责人现在可以安排大家排队的顺序,由于收了好处,所以他要让1号尽量靠前,如果此时还有多种情况,就再让2号尽量靠前,如果还有多种情况,就让3号尽量靠前,以此类推。
那么你就要安排大家的顺序。我们保证一定有解。
Input
第一行一个整数T(1 <= T <= 5),表示测试数据的个数。
然后对于每个测试数据,第一行有两个整数n(1 <= n <= 30000)和m(1 <= m <= 100000),分别表示人数和约束的个数。
然后m行,每行两个整数a和b,表示有一个约束a号必须在b号之前。a和b必然不同。
Output
对每个测试数据,输出一行排队的顺序,用空格隔开。
Sample Input
1
5 10
3 5
1 4
2 5
1 2
3 4
1 4
2 3
1 5
3 5
1 2
Sample Output
1 2 3 4 5
拓扑排序。。
#include<algorithm> #include<iostream> #include<cstdlib> #include<cstring> #include<cstdio> #include<vector> #include<queue> #include<map> using std::map; using std::min; using std::find; using std::pair; using std::queue; using std::vector; using std::multimap; using std::priority_queue; #define pb(e) push_back(e) #define sz(c) (int)(c).size() #define mp(a, b) make_pair(a, b) #define all(c) (c).begin(), (c).end() #define iter(c) __typeof((c).begin()) #define cls(arr, val) memset(arr, val, sizeof(arr)) #define cpresent(c, e) (find(all(c), (e)) != (c).end()) #define rep(i, n) for(int i = 0; i < (int)n; i++) #define tr(c, i) for(iter(c) i = (c).begin(); i != (c).end(); ++i) const int N = 30010; const int INF = 0x3f3f3f3f; struct cmp { inline bool operator()(int &a, int &b) { return a < b; } }; struct TopSort { struct edge { int to, next; }G[N * 8]; int tot, inq[N], head[N], topNum[N]; inline void init(int n) { tot = 0; rep(i, n + 1) { head[i] = -1; inq[i] = topNum[i] = 0; } } inline void add_edge(int u, int v) { G[tot] = (edge){ v, head[u] }; head[u] = tot++; G[tot] = (edge){ u, head[v] }; head[v] = tot++; } inline void built(int m) { int u, v; while(m--) { scanf("%d %d", &u, &v); inq[u]++, add_edge(v, u); } } inline void bfs(int n) { int k = 0; priority_queue<int, vector<int>, cmp> q; rep(i, n) { if(!inq[i + 1]) { q.push(i + 1); } } while(!q.empty()) { int u = q.top(); q.pop(); topNum[k++] = u; for(int i = head[u]; ~i; i = G[i].next) { edge &e = G[i]; if(--inq[e.to] == 0) { q.push(e.to); } } } for(int i = k - 1; ~i; i--) printf("%d%c", topNum[i], i > 0 ? ' ' : ' '); } inline void solve(int n, int m) { init(n), built(m), bfs(n); } }go; int main() { #ifdef LOCAL freopen("in.txt", "r", stdin); freopen("out.txt", "w+", stdout); #endif int t, n, m; scanf("%d", &t); while(t--) { scanf("%d %d", &n, &m); go.solve(n, m); } return 0; }