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;
    }
    越自律,越自由
  • 相关阅读:
    【Golang基础总结】数组和切片的比较
    如何转载别人的文章
    C语言字节对齐问题详解
    幷查集拓展
    贪心
    dfs
    Trie
    哈夫曼树
    bfs
    并查集
  • 原文地址:https://www.cnblogs.com/ha-chuochuo/p/13435572.html
Copyright © 2011-2022 走看看