拓扑排序 (模板)

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

 

posted @ 2019-08-01 16:43  愉也  阅读(179)  评论(0编辑  收藏  举报