1385E 2000的题
题意:给你一个图,n个点,m条边,但这m条边有些是定向的,有些是未定向的,需要你去决定方向,问你是否能让这个图不形成环,而且要对所有未定向的边定向。
思路:拓扑排序可以判断一个图是否是有向无环的,所以可以用到,先对以定向的边进行判断是否已经形成了环,如果形成了环那就肯定不能符合条件,反之,如果未形成环,那么就一定能符合条件,按照拓扑排序出来的顺序,可以用一个数组pos记录,当pos【x】<pos【y】时,即意味着x在y之前就出来了,所以可以加上x->y的一条边是对这个图的是否有环是没有影响的。代码就出来了
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <unordered_map>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
#define rep(i, a, n) for(int i = a; i <= n; i++)
#define per(i, a, n) for(int i = n; i >= a; i--)
#define IOS std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define fopen freopen("file.in","r",stdin);freopen("file.out","w",stdout);
#define fclose fclose(stdin);fclose(stdout);
#define PI 3.14159265358979323846
const int inf = 1e9;
const ll onf = 1e18;
const int maxn = 2e5+10;
inline int read(){
int x=0,f=1;char ch=getchar();
while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
while (ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+(ch^48);ch=getchar();}
return x*f;
}
std::vector<int> g[maxn];
inline void cf(){
int t = read();
while(t--){
int n=read(), m=read();
std::vector<pii> edges;
std::vector<int> in(n+1);
std::vector<int> pos(n+1);
for(int i = 1; i <= n; i++){
g[i].clear();pos[i]=in[i]=0;
}
edges.clear();
for(int i = 0; i < m; i++){
int x=read(), u=read(), v=read();
if(x==1){
g[u].push_back(v);
in[v]++;
}
edges.push_back({u,v});
}
// 典型的拓扑排序
queue<int> q;
int cnt = 0;
for(int i = 1; i <= n; i++){
if(in[i]==0) q.push(i);
}
while(!q.empty()){
int u = q.front();
q.pop();
pos[u] = ++cnt; //记录拓扑的顺序
for(auto to : g[u]){
in[to]--;
if(in[to]==0) q.push(to);
}
}
if(cnt==n){
printf("YES\n");
for(auto [x,y] : edges){
if(pos[x] <= pos[y]) printf("%d %d\n", x, y);
else printf("%d %d\n", y, x);
}
}else printf("NO\n");
}
return ;
}
signed main(){
cf();
return 0;
}