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"