POJ 2367 拓扑排序

来源:互联网 发布:亨德尔 水上音乐 知乎 编辑:程序博客网 时间:2024/06/06 01:33

2367为了找到没有长辈的,或者长辈已经在列表中的人,只需要用拓扑排序就可以很快速地解决

拓扑排序我借鉴了wiki上Kahn的伪代码:

L← Empty list that will contain the sorted elementsS ← Set of all nodes with no incoming edgeswhile S is non-empty do    remove a node n from S    insert n into L    foreach node m with an edge e from nto m do        remove edge e from thegraph        ifm has no other incoming edges then            insert m into Sif graph has edges then    return error (graph has at least onecycle)else    return L (a topologically sortedorder)

下面是我写的程序的源码

#include <iostream>#include <cmath>#include <cstdio>#include <string>#include <vector>#include <cstdlib>#include <algorithm>#include <stack>#include <queue>#include <list>#include <set>#include <map>#include <climits>/*    INT_MAX    LONG_MAX    LLONE_MIN    INT_MIN    ULLONG_MIN*/using namespace std;typedef long long ll;int n;list<int > children[110];int indegree[110];void init(){    for(int i=0;i<110;i++){        children[i].clear();        indegree[i]=0;    }    for(int i=1;i<=n;i++){        int j=1;        while(1){            scanf("%d",&j);            if(!j)break;            indegree[j]++;            children[i].push_back(j);        }    }}void kahn(){    queue<int > noFather;    for(int i=1;i<=n;i++)        if(!indegree[i])noFather.push(i);    list<int > ans;    while(!noFather.empty()){        int node=noFather.front();        noFather.pop();        ans.push_back(node);        for(list<int>::iterator it= children[node].begin();                                it!=children[node].end();it++){            if(!(--indegree[*it]))noFather.push(*it);        }        children[node].clear();    }     for(list<int>::iterator it= ans.begin();                                it!=ans.end();it++)            printf("%d ",*it);}int main(){    while(cin>>n){        init();        kahn();    }    return 0;}
0 0
原创粉丝点击