zoukankan      html  css  js  c++  java
  • 拓扑排序 (模板)

    vector
    #include<bits/stdc++.h>
    using namespace std;
    
    int n, m;
    int mp[505][505];
    int ind[505];
    
    void topo()
    {
        //用优先队列  要求输出编号小的队伍在前
        priority_queue<int,vector<int>,greater<int> >Q; 
        //入度为0的点
        for(int i = 1; i <= n; i++)  //所有的点 
            if(ind[i] == 0)
                Q.push(i);
        int first = 1;
        while(!Q.empty()) {
            int num = Q.top();
            Q.pop();
            ind[num] = -1;
            if(first) cout << num;
            else cout << " " << num;
            first = 0;
            for(int i = 1; i <= n; i++) {
                if(mp[num][i] == 1) {
                    ind[i] -= 1;
                    if(ind[i] == 0)
                        Q.push(i);
                }
            }
        }
        cout << endl;
    }
    int main()
    {
        while(cin >> n >> m) {
            memset(mp,0,sizeof(mp));
            memset(ind,0,sizeof(ind));
            for(int i = 0; i < m; i++) {
                int a, b;
                scanf("%d%d",&a,&b);
                if(mp[a][b] == 0) {
                    mp[a][b] = 1;
                    ind[b]++;
                }
            }
            topo();    
        }
        return 0;
    }
    优先队列 无vector
  • 相关阅读:
    2017.11.20
    第8次
    作业 lianxi
    java 7个练习题
    java 2.15
    java 2.6
    jsp变量和方法的声明
    jsp 基本标签从头练习
    15
    14
  • 原文地址:https://www.cnblogs.com/JiaaaaKe/p/11283601.html
Copyright © 2011-2022 走看看