[题解]CF1385E

题意

给出一张图, 图中有的边已确定方向(且不可更改), 另一些边尚未确定方向. 给所有未确定方向的边指定一个方向, 使得新的图不存在环. 如果无解输出NO

分析

一张图的拓扑排序是一个DAG. 我们首先仅考虑原图的有向边, 如果其中存在环那么无解. 否则求原图的拓扑序, 按拓扑序指派边的方向即可.

代码

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
#include <bits/stdc++.h>
using namespace std;
const int maxm = 4e5+10;
const int maxn = 2e5+10;
struct Edge{
int f,t,next;
Edge(int f = 0,int t = 0,int next = 0):f(f),t(t),next(next){}
}edge[maxm];
int cnt,head[maxm],vis[maxm],dep[maxn],in[maxn],dict[maxn];
void addedge(int f,int t){
edge[cnt] = Edge(f,t,head[f]);
head[f] = cnt++;
}
bool ok = 1;
pair<int,int>Node[maxn];
void BFS(int n){
int qwq = 0;
queue<int>q;
for(int i = 1;i <= n;i++)if(!in[i]){
q.push(i);
vis[i] = 1;
dep[i] = 0;
}
if(q.empty())ok = 0;
while(!q.empty()){
int u = q.front();
q.pop();
dep[u] = ++qwq;
for(int i = head[u];~i;i = edge[i].next){
int v = edge[i].t;
if(--in[v]){
continue;
}
q.push(v);
}
}
if(qwq != n)ok = 0;
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while(t--){
ok = 1;
int n,m;
cin >> n >> m;
for(int i = 0;i <= n;i++){
head[i] = -1;
dep[i] = dict[i] = in[i] = vis[i] = 0;
}
for(int i = 1;i <= m;i++){
int opt,f,t;
cin >> opt >> f >> t;
Node[i] = {f,t};
if(opt){
addedge(f,t);
in[t]++;
dict[i] = 1;
}
}
BFS(n);
if(!ok){
cout << "NO\n";
}
else{
cout << "YES\n";
for(int i = 1;i <= m;i++){
int & f = Node[i].first,& t = Node[i].second;
if(dep[f] > dep[t])cout << t << " " << f << endl;
else cout << f << " " << t << endl;
}
}
}

return 0;
}