題目: UVa - 10305 - Ordering Tasks
題目說明
給一整數 N
代表有 N
個任務要完成,及 M
個規則,表示在做某個任務前需要完成的任務。求適合的執行任務順序 ( 符合規則即可 )。
Input: 每組測資第一行為兩個整數 N
、M
,若 N
、M
皆為 0 表示結束。否則接下來 M
行,每行都有兩個整數 a
、b
,表示在做任務 b
前需要先完成任務 a
。
Output: 符合規則的任務執行順序。
解題思路
基本的 Topological sort,建圖之後做 DFS 即可。
參考解法
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 53 54 55 56 57
| #include <iostream> #include <functional> #include <vector> #include <list>
using namespace std;
#define LOOP(n) for(int I = 0; I < n; ++I) #define SIZE(c) int(c.size())
static auto __ = [] { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); return 0; }();
int main() { int N, M; int mem[101]; int visited[101]; vector<int> G[101]; list<int> ret;
function<void(int)> dfs = [&](int n) { if (visited[n]) return; visited[n] = 1; for (auto& i : G[n]) dfs(i); ret.push_front(n); };
while (cin >> N >> M && (N || M)) { ret.clear(); fill(mem, mem + 101, 0); fill(visited, visited + 101, 0); fill(G, G + 101, vector<int>());
LOOP(M) { int a, b; cin >> a >> b; G[a].push_back(b); mem[b] = 1; }
for (int i = 1; i <= N; ++i) if (!mem[i]) dfs(i);
cout << ret.front(); for (auto it = ++ret.begin(); it != ret.end(); ++it) cout << " " << *it; cout << '\n'; } }
|