Topic Source: Luo Gu
Title Description
Is a schematic view of a food web ecosystem, according to FIG Answer first small chain shown in FIG. Now you question and n and m species energy flow relationship, which find food. Species name is numbered from 1 to n relationship between the M-shaped flow of energy such as a1 b1a2 b2a3 b3 ...... am-1 bm-1am bm ai bi where ai represents the energy flow from the bi species species, a single note isolated not a biological food chain
Input and output formats
Input formats:
The first line of two integers n and m, each row next two rows ai bi integers m and m describe the relationship between the flow of energy. (Data of input data symbols to ensure biological characteristics, do not have duplicate energy flow relations) 1 <= N <= 100000 0 <= m <= 200000 Title answer guaranteed not burst int
Output formats:
An integer that is the number of food chains in the food web
Sample input and output
10 16 1 2 1. 4 1 10 2. 3 2. 5 . 4. 3 . 4. 5 . 4. 8 . 6. 5 . 7. 6 . 7. 9 . 8. 5 . 9. 8 10. 6 10. 7 10. 9
outputs Sample # 1:
9
Analysis:
This problem may also dp, relatively water.
I wrote a topological sort of naked, not much to say.
Specifically look at the code.
Note: d [] storage is through the food chain at a point number. Moreover, this question has eight test points are presented with isolated nodes, do not ask me how I know.
Reference Code:
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<string> #include<cstdlib> #include<queue> #include<vector> #define INF 0x3f3f3f3f #define PI acos(-1.0) #define N 100010 #define MOD 2520 #define E 1e-12 using namespace std; queue<int> q; struct rec{ int next,ver; G} [N <<2 ]; int head [N], TOT, n-, m, ING [N], CNT, D [N]; BOOL V [N << 2 ]; void the Add ( int X, int Y) { G [ ++ TOT] .ver = Y; G [TOT] .next = head [X], head [X] = TOT; ING [Y] ++; // can count on the degree of this time } int main () { Scanf ( " % D% D " , & n-, & m); for ( int I = . 1 ; I <= m; I ++ ) { int X, Y; Scanf ( " % D% D " , & X, & Y); IF (X == Y) Continue ; the Add (X, Y); } for ( int I = . 1 ; I <= n-; I ++ ) IF (ING [ I] == 0 ! && head [I] = 0 ) q.push (I), D [I] = . 1 ; // can head [] Analyzing an isolated point the while (q.size ()) // bare topology { int X = q.front (); q.pop (); IF (head [X] == 0 ) = CNT + D [X]; // still show a head batch of [] is determined that edge for ( int I = head [X] ; i; i = G [I] .next) { int Y = G [I] .ver; D [Y] + = D [X]; // accumulated through the food chain of the number of points IF (Ing [Y] = = 0 ) q.push (Y); } } COUT << CNT << endl; return 0 ; }