This page is still under construction.

Parts of this page are still being built. What you see may change.

Median Weight Bead

Interview

Time limit1sMemory limit128 MB

Summary
Given weighted comparisons between beads, count how many beads cannot be the median because at least (N+1)/2 beads are known heavier or lighter.
Level

Medium5 of 10

Topics
Graph, DFS, Dynamic programming, Implementation
Solved
No attempts yet

Problem

There are NN beads of the same shape and size but with different weights. NN is odd, and the beads are labeled 1,2,…,N1, 2, \dots, N. Your task is to identify the bead whose weight is the median — the N+12\frac{N+1}{2}-th lightest bead among all NN beads.

A scale lets us compare any two beads and decide which is heavier. After MM comparisons we know that some beads are heavier than others, and this relation is transitive: if bead AA is heavier than bead BB and bead BB is heavier than bead CC, then AA is heavier than CC. Using only this information, we want to discard every bead that can never be the median.

A bead can never be the median if at least N+12\frac{N+1}{2} other beads are known to be heavier than it, or at least N+12\frac{N+1}{2} other beads are known to be lighter than it.

For example, suppose N=5N = 5 with the following M=4M = 4 results:

  1. Bead 2 is heavier than Bead 1.
  2. Bead 4 is heavier than Bead 3.
  3. Bead 5 is heavier than Bead 1.
  4. Bead 4 is heavier than Bead 2.

We still cannot tell exactly which bead is the median, but Bead 1 and Bead 4 can never be it: Beads 2, 4, and 5 are all heavier than Bead 1, and Beads 1, 2, and 3 are all lighter than Bead 4. Since N+12=3\frac{N+1}{2} = 3, both beads meet the removal condition.

Write a program that counts how many beads can never be the median.

Input

The first line contains an integer tt (1≤t≤111 \le t \le 11), the number of test cases. The data for each test case follows.

The first line of each test case contains two integers NN (1≤N≤991 \le N \le 99) and MM, where NN is the number of beads and MM is the number of comparisons. Each of the next MM lines contains two integers aa and bb, meaning that bead aa is heavier than bead bb.

Output

For each test case, print a single line containing the number of beads that can never be the median.

Examples3

  1. Example 1

    Input
    1
    5 4
    2 1
    4 3
    5 1
    4 2
    
    Expected output
    2
    
  2. Example 2

    Input
    1
    1 0
    
    Expected output
    0
    
  3. Example 3

    Input
    1
    3 2
    3 2
    2 1
    
    Expected output
    2