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
| #include <iostream> #include <cstring> using namespace std; const int N = 200001, M = 200001; int T; int n, m, k; int h[N], e[M], ne[M], idx; int d[N], q[N]; int pos[N]; struct Edge { int a, b; } edge[M]; void add(int a, int b) { e[idx] = b, ne[idx] = h[a], h[a] = idx++; } bool topsort() { int hh = 0, tt = -1; for (int i = 1; i <= n; ++i) if (!d[i]) q[++tt] = i; while (hh <= tt) { int t = q[hh++]; for (int i = h[t]; ~i; i = ne[i]) { int j = e[i]; if (--d[j] == 0) q[++tt] = j; } } return tt == n - 1; } int main() { scanf("%d", &T); while (T--) { scanf("%d%d", &n, &m); memset(h, -1, (n + 1) * 4); memset(d, 0, (n + 1) * 4); idx = k = 0; while (m--) { int t, a, b; scanf("%d%d%d", &t, &a, &b); if (!t) edge[k++] = {a, b}; else { add(a, b); ++d[b]; } } if (!topsort()) puts("NO"); else { puts("YES"); for (int i = 1; i <= n; ++i) for (int j = h[i]; ~j; j = ne[j]) printf("%d %d\n", i, e[j]); for (int i = 0; i < n; ++i) pos[q[i]] = i; for (int i = 0; i < k; ++i) { int a = edge[i].a, b = edge[i].b; if (pos[a] > pos[b]) swap(a, b); printf("%d %d\n", a, b); } } } return 0; }
|