#P3183. Counting Food Chains in an Ecosystem

    ID: 16440 Type: Default 1000ms 256MiB

Counting Food Chains in an Ecosystem

Counting Food Chains in an Ecosystem

In an ecosystem, the food web describes the energy flow among different species. Given n species numbered from 1 to n and m energy flow relationships, you are to count the number of food chains. Each energy flow is given as a pair of numbers ai and bi (for i = 1, 2, \ldots, m), indicating that energy flows from species ai to species bi. Note that a species that is isolated (i.e. not involved in any energy flow) does not constitute a food chain. In other words, only components having at least two species (directly or indirectly connected via energy flows) form a valid food chain.

Definition:

  • Consider an undirected connection between two species if there is an energy flow (in either direction) between them.
  • A food chain is defined as a connected component (under the undirected interpretation) that contains at least two species.
  • Your task is to count such connected components.
  • </p>

    inputFormat

    The first line contains two integers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ 105), representing the number of species and the number of energy flow relationships respectively.

    The second line contains 2*m integers: a1 b1 a2 b2 \ldots am bm, where each pairing represents an energy flow from species ai to species bi.

    outputFormat

    Output a single integer representing the number of food chains (i.e. the number of connected components with at least two species) in the ecosystem.

    sample

    5 3
    1 2 2 3 4 5
    
    2