Simple topsort, not explained!
You can use a queue for traversal!
# Include <vector> # include <list> # include <map> # include <set> # include <queue> # include <string. h> # include <deque> # include <stack> # include <bitset> # include <algorithm> # include <functional> # include <numeric> # include <utility> # include <sstream> # include <iostream> # include <iomanip> # include <cstdio> # include <cmath> # include <cstdlib> # include <limits. h> using namespace STD; int lowbit (INT t) {return T & (-T);} in T countbit (INT t) {return (t = 0 )? 0 :( 1 + countbit (T & (t-1);} int gcd (int A, int B) {return (B = 0 )? A: gcd (B, A % B) ;}# define ll long # define PI ACOs (-1.0) # define n 1000010 # define Max int_max # define min int_min # define EPS 1e-8 # define fre freopen ("a.txt", "r", stdin) int G [110] [110]; int in [110]; int N, CNT; int ans [110]; void topsort () {int I, j, k; CNT = 0; /* for (I = 1; I <= N; I ++) {// traverse n times for (j = 1; j <= N; j ++) if (in [J] = 0) {ans [CNT ++] = J; in [J] =-1; break;} For (k = 1; k <= N; k ++) if (G [J] [k]) in [k] --;} */queue <int> q; for (I = 1; I <= N; I ++) if (in [I] = 0) {q. push (I); in [I] =-1; break;} while (! Q. empty () {int x = Q. front (); q. pop (); ans [CNT ++] = x; for (I = 1; I <= N; I ++) {If (G [x] [I]) in [I] --; If (in [I] = 0) {in [I] =-1; q. push (I) ;}}} int main () {int I, j, k; while (scanf ("% d", & N )! = EOF) {memset (in, 0, sizeof (in); memset (G, 0, sizeof (g); for (I = 1; I <= N; I ++) {int A; while (scanf ("% d", & A) {G [I] [a] = 1; in [a] ++ ;}} topsort (); printf ("% d", ANS [0]); for (I = 1; I <CNT; I ++) printf ("% d", ANS [I]); puts ("") ;}return 0 ;}