zoukankan      html  css  js  c++  java
  • 拓扑排序

    #include <bits/stdc++.h>
    using namespace std;
    
    const int maxn = 5e5 + 10;
    int N, M;
    int h[maxn], v[maxn], in[maxn], nx[maxn];
    int  sz = 0;
    
    void init() {
        for(int i = 1; i <= N; i ++) {
            h[i] = -1;
            in[i] = 0;
        }
        sz = 0;
    }
    
    void add(int a, int b) {
        v[sz] = b;
        nx[sz] = h[a];
        h[a] = sz;
        in[b] ++;
        sz ++;
    }
    
    void TopSort() {
        queue<int> q;
        vector<int> ans;
    
        for(int i = 1; i <= N; i ++) {
            if(in[i] == 0)
                q.push(i);
        }
    
        while(!q.empty()) {
            int tp = q.front();
            q.pop();
            ans.push_back(tp);
    
            for(int i = h[tp]; i != -1; i = nx[i]) {
                in[v[i]] --;
                if(in[v[i]] == 0)
                    q.push(v[i]);
            }
        }
    
        if(ans.size() != N)
            printf("NO
    ");
        else {
            for(int i = 0; i < ans.size(); i ++)
                printf("%d%s", ans[i], i != ans.size() - 1 ? " " : "
    ");
        }
    
    }
    
    int main() {
        while(~scanf("%d%d", &N, &M)) {
            init();
            for(int i = 0; i < M; i ++) {
                int a, b;
                scanf("%d%d", &a, &b);
                add(a, b);
            }
            TopSort();
        }
        return 0;
    }
    

      see u again

  • 相关阅读:
    Dictionary用法详解
    List与IList的区别
    接口
    C# List<T>用法详解
    c#FileStream文件读写
    学习如何用VS2010创建ocx控件
    sql server零碎知识
    BinaryWriter和BinaryReader用法
    通讯录源程序分析
    美丽说
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10743897.html
Copyright © 2011-2022 走看看