Codeforces Round #656 (Div. 3) (E. Directing Edges)(拓扑排序)

题目描述 

You are given a graph consisting of nn vertices and mm edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges.

You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges.

You have to answer tt independent test cases.

题目大意:

一共有n个点,m条边,其中有的是无向边,有的是有向边,让你将无向边变成有向边,且该图不能存在环。

思路:

除去无向边,如果由所有有向边构成的图是有环的,则直接输出NO,否则就可以改变无向边使其无环。由此,首先可以通过跑一次拓扑排序,来确定是否有环,以及确定所有点的拓扑序,只要将无向边按照拓扑序变成有向边即可。

代码:

#include<bits/stdc++.h>
#define ll long long
#define MOD 998244353 
#define INF 0x3f3f3f3f
#define mem(a,x) memset(a,x,sizeof(a))  
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
const int MAXN=200005;
int in[MAXN];
int u[MAXN],v[MAXN];
int cnt[MAXN];
vector<int>edge[MAXN];
int n,m;
int num=0;
void init()
{
    for(int i=0;i<=n;i++){
        in[i]=0;
        cnt[i]=0;
        edge[i].clear();
        num=0;
    }
}
void topsort()
{
    queue<int>q;
    for(int i=1;i<=n;i++){
        if(in[i]==0){
            q.push(i);
        }
    }
    while(!q.empty()){
        int p=q.front();
        q.pop();
        cnt[p]=++num;
        for(auto i:edge[p]){
            in[i]--;
            if(in[i]==0)q.push(i);
        }
    }
}
int main()
{
    int t;
    cin>>t;
    while(t--){
        cin>>n>>m;
        init();
        int p;
        for(int i=1;i<=m;i++){
           scanf("%d %d %d",&p,&u[i],&v[i]);
           if(p==1){
              edge[u[i]].push_back(v[i]);
              in[v[i]]++;
           }
        }
        topsort();
        if(num<n){       //原图就有环
            cout<<"NO"<<endl;
        }else{
            cout<<"YES"<<endl;
            for(int i=1;i<=m;i++){
                    if(cnt[u[i]]<cnt[v[i]]){
                        printf("%d %d\n",u[i],v[i]);
                    }else{
                        printf("%d %d\n",v[i],u[i]);
                    }
            }
        }
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值