紫书UVA 10305

拓扑排序水题,但因为没做好邻接阵的初始化导致WA了几发,以后一定要注意初始化!!!

#include<bits/stdc++.h>

using namespace std;
#define maxn 1000
vector<int> G[maxn];
int in[maxn];           //入度
int topo[maxn], t,n,m;
void init()
{
    memset(in,0,sizeof(in));
    memset(topo,0,sizeof(topo));
    for(int i=0;i<maxn;i++)//此处原来没写导致WA
    {
        G[i].clear();
    }
}
bool topoSort() {
    priority_queue<int, vector<int>, greater<int> > q; t = 0; //优先队列保证最小序列
    for(int i = 1; i <= n; ++i) {
        if(in[i] == 0) q.push(i);
    }

    int cnt = 0;
    while(!q.empty()) {
        int u = q.top(); q.pop();
        topo[t++] = u; ++cnt;
        for(int v = 0; v < G[u].size(); ++v) {
            if(--in[G[u][v]] == 0) q.push(G[u][v]);             //找入度为0的边入队
        }
    }

    if(cnt != n) return 0;                                      //有环
    return 1;
}
int main()
{
    while(cin>>n>>m&&(m||n))
    {
        init();
        for(int i=0;i<m;i++)
        {
            int u,v;
            cin>>u>>v;
            G[u].push_back(v);
            in[v]++;
        }
        topoSort();
        for(int i=0;i<t;i++)
        {
            if(i==0)
            cout<<topo[i];
            else
                cout<<" "<<topo[i];
        }
        cout<<endl;
    }
    return 0;
}

posted @ 2018-04-30 09:07  MCQ  阅读(104)  评论(0编辑  收藏  举报