Median Weight Bead
InterviewTime limit1sMemory limit128 MB
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 beads of the same shape and size but with different weights. is odd, and the beads are labeled . Your task is to identify the bead whose weight is the median — the -th lightest bead among all beads.
A scale lets us compare any two beads and decide which is heavier. After comparisons we know that some beads are heavier than others, and this relation is transitive: if bead is heavier than bead and bead is heavier than bead , then is heavier than . 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 other beads are known to be heavier than it, or at least other beads are known to be lighter than it.
For example, suppose with the following results:
- Bead 2 is heavier than Bead 1.
- Bead 4 is heavier than Bead 3.
- Bead 5 is heavier than Bead 1.
- 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 , 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 (), the number of test cases. The data for each test case follows.
The first line of each test case contains two integers () and , where is the number of beads and is the number of comparisons. Each of the next lines contains two integers and , meaning that bead is heavier than bead .
Output
For each test case, print a single line containing the number of beads that can never be the median.