zoukankan      html  css  js  c++  java
  • 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
    ",u[i],v[i]);
                        }else{
                            printf("%d %d
    ",v[i],u[i]);
                        }
                }
            }
        }
        return 0;
    }
    越自律,越自由
  • 相关阅读:
    一类涉及矩阵范数的优化问题
    MATLAB小实例:读取Excel表格中多个Sheet的数据
    深度多视图子空间聚类
    具有协同训练的深度嵌入多视图聚类
    结构深层聚类网络
    一种数据选择偏差下的去相关聚类方法
    shell编程基础二
    shell编程基础一
    如何处理Teamcenter流程回退情况
    汽车行业数字化车间解决方案
  • 原文地址:https://www.cnblogs.com/ha-chuochuo/p/13435572.html
Copyright © 2011-2022 走看看