Sdnu 1089. Topology Sort "node topology ordering with 0 in degrees"

Source: Internet
Author: User
Tags in degrees

1089. Topology sequencingDescription given a graph, if the graph is not ring, then it is sorted and output topology, otherwise output imposable. Input first behavior two integers n (1<=n<=1000), M (1<=m<=100000);
After M lines, each line of two integers A and b represents a forward edge from A to B. Output if there is a ring, outputs imposable, otherwise the output line with a space-separated topological sorting results, if there are multiple results, the output dictionary order of the smallest. Sample Input
5 41 22 33 44 5
Sample Output
1 2 3) 4 5
A node that has an entry level of 0 each time it is found.
#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++)//The node with the 0-per-entry degree if (out[i]==0&&c[i]==0) {c[i]=1; x=i; Key=true;            Break } if (Key==false) return false;//exists ring 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;}


Sdnu 1089. Topology Sort "node topology ordering with 0 in degrees"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.