#P8276. [USACO22OPEN] Hoof and Brain P

[USACO22OPEN] Hoof and Brain P

Problem Description

You are given a directed graph with NN nodes and MM edges (2N1052 \leq N \leq 10^5, 1M21051 \leq M \leq 2 \cdot 10^5). Farmer John’s cows like to play the following two-player game.

Place two tokens on different nodes of the graph (you may use some cow-related items instead of tokens). Each turn, one player, Brain, chooses a token that must be moved along one outgoing edge. The other player, Hoof, chooses which outgoing edge to use to move that token. The two tokens are not allowed to be on the same node at any time. If at some point Hoof cannot make a legal move, then Brain wins. If the game can continue forever, then Hoof wins.

You are given QQ queries (1Q1051 \leq Q \leq 10^5), each containing the initial nodes of the two tokens. For each query, output which player wins.

Input Format

The first line contains NN and MM.

The next MM lines each contain two integers aa and bb, representing an edge from aa to bb.

The graph contains no self-loops or multiple edges.

The next line contains QQ.

The last QQ lines each contain two integers xx and yy, satisfying 1x,yN1\le x,y\le N and xyx\neq y, representing the initial nodes of the tokens.

Output Format

Output a string of length QQ. The character B means Brain wins, and H means Hoof wins.

Note: the time limit for this problem is 4 seconds, which is twice the usual limit.

9 10
1 2
2 3
3 4
4 7
3 5
1 6
6 8
8 9
9 6
7 2
4
1 5
1 2
1 6
2 4
BHHB

Hint

Constraints

Brain can win the first game by choosing node 55; then Hoof will have no legal move.

Brain can win the last game by choosing node 44 and then choosing node 77; then Hoof will have no legal move.

Hoof wins the other games.

Test Point Properties

  • Test points 2-3 satisfy N100N\le 100, M200M\le 200.
  • Test points 4-9 satisfy N5000N\le 5000.
  • Test points 10-21 have no additional constraints.

Translated by ChatGPT 5