최종 순위
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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | #include <stdio.h> #include <string.h> #include <queue> #include <vector> using namespace std; int tc, n, m, a, b; int mat[501][501], order[501], in[501]; int main() { scanf("%d", &tc); while (tc--) { memset(mat, 0, sizeof(mat)); memset(in, 0, sizeof(in)); scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d", &order[i]); for (int i = 1; i <= n; ++i) { for (int j = i + 1; j <= n; ++j) { mat[order[i]][order[j]] = 1; in[order[j]]++; } } scanf("%d", &m); for (int i = 0; i < m; ++i) { scanf("%d %d", &a, &b); if (mat[a][b]) { mat[a][b] = 0; mat[b][a] = 1; in[b]--, in[a]++; } else { mat[b][a] = 0; mat[a][b] = 1; in[a]--, in[b]++; } } queue<int> q; for (int i = 1; i <= n; ++i) if (!in[i]) q.push(i); bool certain = true; vector<int> ans; while (!q.empty()) { if (q.size() > 1) { certain = false; break; } int cur = q.front(); q.pop(); ans.push_back(cur); for (int next = 1; next <= n; ++next) { if (mat[cur][next]) { in[next]--; if (!in[next]) q.push(next); } } } if (!certain) //uncertain puts("?"); else if (ans.size() == n) { //possible for (int i = 0; i < n; ++i) printf("%d ", ans[i]); puts(""); } else //impossible puts("IMPOSSIBLE"); } return 0; } | cs |
'알고리즘 > Topological sort 위상정렬' 카테고리의 다른 글
백준) 2637 장난감조립 (0) | 2018.02.21 |
---|---|
백준) 9470 Strahler 순서 (0) | 2018.02.21 |
백준) 1005 ACM Craft (0) | 2018.02.21 |
백준) 1516 게임 개발 (0) | 2018.02.20 |
백준) 2623 음악프로그램 (0) | 2018.02.20 |