SDNU 1089.拓撲排序【找入度為0的節點 拓撲排序】,sdnu入度

來源:互聯網
上載者:User

SDNU 1089.拓撲排序【找入度為0的節點 拓撲排序】,sdnu入度
1089.拓撲排序Description給定一個有向圖,若圖無環,則將其進行拓撲排序並輸出,否則輸出IMPOSABLE。Input第一行為兩個整數n(1<=n<=1000)、m(1<=m<=100000);
之後m行,每行兩個整數a、b表示一條從a到b的有向邊。Output若存在環,輸出IMPOSABLE,否則輸出一行用一個空格隔開的拓撲排序的結果,若存在多個結果,輸出字典序最小的。Sample Input

5 41 22 33 44 5
Sample Output
1 2 3 4 5
每次找入度為0的節點。
#include<cstdio>#include<cstring>#include<vector>#include<string>#include<iostream>using namespace std;const int maxn=1010;int out[maxn]={0},c[maxn]={0},n,m,x,cnt=0;vector<int>G[maxn];vector<int>topo;bool toposort(){    while(cnt!=n){        bool key=false;        for(int i=1;i<=n;i++)//每次找入度為0的節點            if(out[i]==0&&c[i]==0){                c[i]=1; x=i;                key=true; break;            }        if(key==false) return false;//存在環        topo.push_back(x); cnt++;        for(int i=0;i<G[x].size();i++)            out[G[x][i]]--;    }    return true;}int main(){    scanf("%d%d",&n,&m);    int u,v;    for(int i=0;i<m;i++){        scanf("%d%d",&u,&v);        G[u].push_back(v);        out[v]++;    }    if(toposort()){        for(int i=0;i<n;i++){            if(i!=0) printf(" ");            printf("%d",topo[i]);        }        printf("\n");    }    else printf("IMPOSABLE\n");    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.