Topic link
Topic outline: Topic outline: Give you a graph with n vertices and m edges. Some of the edges are not reversed, and the others have directions. Let you assign a direction to each edge. The final graph must not form a self-loop. (No re-edge)
Idea: First of all, I didn't know the topological sorting before, and I knew it through this question. At the beginning, my idea was to check and judge the ring together, but I couldn't see the direction. I know the topological sorting only after reading the solutions of others.
Attached here is the topological sorting in Baidu Encyclopedia. This
question is obviously not working if it has a loop itself. This is also the easiest to think of. Then the remaining direction is for the undirected edge. In order to prevent the newly generated directed edges from forming a ring, a topological sort must be performed first, and then a point with a small topological order is directed to a point with a large topological order, so that a ring will definitely not be formed. why?
Understand this sentence well and you will understand.
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const int N=2e5+10;
struct edge
{
int to,next;
}e[N];
struct node
{
int u,v;
node (int uu=0,int vv=0):u(uu),v(vv){
}
};
int head[N],cnt=0,deg[N],ans[N],num,n,m;
vector<node>f;
void addedge(int u,int v)
{
e[++cnt].to=v;
e[cnt].next=head[u];
head[u]=cnt;
}
void bfs()
{
queue<int>q;
for(int i=1;i<=n;i++) if(deg[i]==0) q.push(i);
while(!q.empty())
{
int now=q.front();q.pop();
num++;
ans[now]=num;
for(int i=head[now];i;i=e[i].next)
{
int to=e[i].to;
deg[to]--;
if(deg[to]==0) q.push(to);
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
f.clear();
memset(deg,0,sizeof(deg));
memset(ans,0,sizeof(ans));
memset(head,0,sizeof(head));
cnt=0;num=0;
int o,x,y;
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&o,&x,&y);
f.push_back(node(x,y));
if(o==1)
{
addedge(x,y);
deg[y]++;
}
}
bfs();
if(num!=n) printf("NO\n");
else
{
printf("YES\n");
for(int i=0;i<(int)f.size();i++)
{
node now=f[i];
if(ans[now.u]<ans[now.v]) printf("%d %d\n",now.u,now.v);
else printf("%d %d\n",now.v,now.u);
}
}
}
return 0;
}