Stock Chase

Time limit1sMemory limit128 MB

Summary
Given share-purchase transactions between companies in order, count how many must be rejected because they would create a cycle.
Level

Medium4 of 10

Topics
Union-find, Graph
Solved
No attempts yet

Problem

I have to admit, the solution I proposed last year for solving the bank cash crisis did not solve the whole economic crisis. As it turns out, companies do not have that much cash in the first place. What they own is mostly shares in other companies.

It is common, and acceptable, for one company to own shares in another. What complicates the issue is for two companies to own shares in each other at the same time. If you think about it for a moment, this means that each company now (indirectly) controls its own shares.

A new market regulation is being put in place: no company may control shares in itself, whether directly or indirectly. For example, imagine company AA buying shares in BB, BB buying shares in CC, and then CC buying shares in AA. The first two purchases are acceptable, but the third must be rejected, since it would make all three companies control their own shares.

The program is given every buying transaction in chronological order. It must reject any transaction that could lead to a company controlling its own shares, and accept all other transactions. Report how many transactions are rejected.

Input

The input consists of one or more test cases. Each test case is given on T+1T + 1 lines. The first line contains two positive integers NN and TT, where NN is the number of companies (0<N≤2340 < N \le 234) and TT is the number of transactions (0<T≤1000000 < T \le 100000). Each of the following TT lines describes one buying transaction as two integers AA and BB (0<A,B≤N0 < A, B \le N), meaning that company AA wants to buy shares in company BB.

The last line of the input contains two zeros.

Output

For each test case, print the following single line:

k. R

where kk is the test case number (starting at one) and RR is the number of transactions that must be rejected.

Examples3

  1. Example 1

    Input
    3 6
    1 2
    1 3
    3 1
    2 1
    1 2
    2 3
    0 0
    
    Expected output
    1. 2
    
  2. Example 2

    Input
    2 1
    1 2
    0 0
    
    Expected output
    1. 0
    
  3. Example 3

    Input
    2 2
    1 2
    2 1
    3 3
    1 2
    2 3
    3 1
    0 0
    
    Expected output
    1. 1
    2. 1