#P7370. Wizard Duel

    ID: 20568 Type: Default 1000ms 256MiB

Wizard Duel

Wizard Duel

In this problem, there are (N) wizards labeled from (1) to (N) and (M) duels. Each duel is described by two integers (A) and (B) meaning that wizard (A) is defeated by wizard (B). The wand is initially held by wizard (1). Whenever the current wand holder (A) loses in a duel against (B), the wand transfers from (A) to (B). All duels must be executed, but their order can be arbitrarily rearranged. Your task is to determine all possible wizards that can be the final owner of the wand if you choose an optimal ordering of duels.

Explanation

The wand can be transferred only when its current owner loses a duel. By reordering the duels, you can choose a sequence such that the wand is transferred along some chain of transfers. Formally, consider a directed graph where an edge \(A \to B\) means that wizard \(A\) loses to wizard \(B\) in one duel. Initially, the wand is at node \(1\). A duel is effective if it occurs when its loser holds the wand. In other words, a wizard \(X\) can be the final owner if and only if there exists a sequence of duels (a path in the graph) starting from \(1\) and ending at \(X\) and it is possible to order the duels so that every duel on that path is effective. Note that if there exists at least one duel where wizard \(1\) loses, then wizard \(1\) cannot remain with the wand unless there is a cycle (a path returning to \(1\)) that can restore the wand to wizard \(1\).

Input/Output Format

inputFormat

The first line contains two integers \(N\) and \(M\) (\(1 \leq N, M \leq 10^5\)).

Each of the following \(M\) lines contains two integers \(A\) and \(B\) (\(1 \leq A, B \leq N\)), denoting that wizard \(A\) loses to wizard \(B\).

outputFormat

Print a single line with the list of all possible final owners of the wand in increasing order, separated by a space.

sample

3 3
1 2
2 3
1 3
2 3