Directing Edges

Directing Edges

Created by LXC on Fri May 10 00:05:58 2024

https://codeforces.com/problemset/problem/1385/E

ranting: 2000

tag: constructive algorithms, dfs and similar, graphs

problem

给定一个由有向边与无向边组成的图,现在需要你把所有的无向边变成有向边,使得形成的图中没有环

如果可以做到请输出该图,否则直接输出”NO”。

注意多组询问

solution

将所有点和有向边建图,再拓扑排序。得到每个点的排序序列。对于任意无向边,根据两个点的在序列中的顺序确定的方向。

code

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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98

#include <bits/stdc++.h>
// #define SINGLE_INPUT
#define ll long long
#define ull unsigned long long
#define N 500005
#define MOD 998244353
using namespace std;

random_device seed;
ranlux48 engine(seed());
int random(int l, int r) {
uniform_int_distribution<> distrib(l, r);
return distrib(engine);
}
template<class t,class u> ostream& operator<<(ostream& os,const pair<t,u>& p) {
return os<<'['<<p.first<<", "<<p.second<<']';
}
template<class t> ostream& operator<<(ostream& os,const vector<t>& v) {
os<<'['; int s = 1;
for(auto e:v) { if (s) s = 0; else os << ", "; os << e; }
return os<<']';
}
template<class t,class u> ostream& operator<<(ostream& os,const map<t,u>& mp){
os<<'{'; int s = 1;
for(auto [x,y]:mp) { if (s) s = 0; else os << ", "; os<<x<<": "<<y; }
return os<<'}';
}


void sol() {
int n, m;
cin >> n >> m;
vector<pair<int,int>> e;
vector<vector<int>> g(n+1);
vector<int> in(n+1);
for (int i=0; i<m; i++) {
int d, x, y;
cin >> d >> x >> y;
if (d) g[x].emplace_back(y), in[y]++;
e.emplace_back(x, y);
}
// cout << g << endl;
// cout << v << endl;
// cout << in << endl;
queue<int> q;
for (int i=1; i<=n; i++) {
if (!in[i]) {
q.push(i);
}
}
vector<int> ord(n+1);
int p = 1;
while (q.size()) {
int u = q.front(); q.pop();
ord[u] = p++;
for (auto v:g[u]) {
if (--in[v]==0) {
q.push(v);
}
}
}
// cout << ord << endl;
for (int i=1; i<=n; i++) {
if (in[i]) {
cout << "NO\n";
return ;
}
}
cout << "YES\n";
for (auto [x, y]:e) {
if (ord[x] < ord[y]) {
cout << x << " " << y << "\n";
} else {
cout << y << " " << x << "\n";
}
}


}

int main() {
cout << setprecision(15) << fixed;
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
#ifndef SINGLE_INPUT
int t;
cin >> t;
while (t--) {
sol();
}
#else
sol();
#endif
return 0;
}