题解1385E Directing Edges

· · 题解

一个图是有向无环图,那么它一定可以拓扑排序。

尝试对图进行拓扑排序。

先给出方法:不管无向边,用有向边计算入度直接拓扑排序,然后无向边边拓扑边连。假设边连接 x,y, 那么在拓扑排序中 x 先出现则连接 x,y。

为什么这样是对的呢?

令某一条无向边为 x,y。

当我们连接 x,y 时,若 y 之前有入度,那么这样肯定更优。否则,y 的入度也不会改变,因为 x 是被删去的点。也就是说,当 x,y 入度均为 0 时,出现的顺序不会影响结果。

#include<bits/stdc++.h>
#define re register
using namespace std;
inline int read(){
    re int t=0;re char v=getchar();
    while(v<'0')v=getchar();
    while(v>='0')t=(t<<3)+(t<<1)+v-48,v=getchar();
    return t;
}
int t,n,m,a[200002],b[200002],ans,head[200002],cnt,rd[200002];
bool vis[200002];
struct edge{
    int to,next,w;
}e[2000002];
inline void add(re int x,re int y,re int z){
    e[++cnt]=(edge){y,head[x],z};
    head[x]=cnt;
}
queue<int>q;
int main(){
    t=read();
    while(t--){
        re int tot=0;
        n=read();m=read();
        for(re int i=1;i<=n;++i)rd[i]=vis[i]=head[i]=0;
        for(re int i=1,x,y,z;i<=m;++i){
            x=read(),y=read(),z=read();
            if(!x){
                add(y,z,1),add(z,y,1);
            }
            else add(y,z,0),++rd[z];
        }
        for(re int i=1;i<=n;++i)if(!rd[i])q.push(i);
        while(!q.empty()){
            re int x=q.front();q.pop();vis[x]=1;
            for(re int i=head[x];i;i=e[i].next){
                if(vis[e[i].to])continue;//printf("%d %d\n",x);
                if(e[i].w)a[++tot]=x,b[tot]=e[i].to;
                else{
                    a[++tot]=x,b[tot]=e[i].to;
                    --rd[e[i].to];
                    if(!rd[e[i].to])q.push(e[i].to);
                }
            }
        }
        if(tot^m)puts("NO");
        else{
            puts("YES");
            for(re int i=1;i<=m;++i){
                printf("%d %d\n",a[i],b[i]);
            }
        }
    }
}