之前用暴力和优先队列做过,但是太占内存

最好的方法还是用vector

不停地更新入度删边,比较容易理解

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
int ind[1005];
vector<int> V[1005];
int n, m;
void init()
{
    memset(ind, 0, sizeof(ind));
    for(int i = 1; i <= n; i ++)
        V[i].clear();
}
void topo()
{
    priority_queue<int, vector<int>, greater<int> >q;
    for(int i = 1; i <= n; i ++)
        if(! ind[i]) q.push(i);
    int cnt = 0;
    while(! q.empty())
    {
        int h = q.top();
        q.pop();
        cnt ++;
        if(cnt != n) printf("%d ", h);
        else printf("%d\n", h);
        for(int i = 0; i < V[h].size(); i ++)
        {
            int e = V[h][i];
            ind[e] --;
            if(! ind[e])
                q.push(e);
        }
    }
}
int main()
{
    while(scanf("%d%d",&n,&m) != EOF)
    {

        init();
        int u, v;
        for(int i = 1; i <= m; i ++)
        {
            scanf("%d%d",&u,&v);
            V[u].push_back(v);
            ind[v] ++;
        }
        topo();
    }
    return 0;
}

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐