Mykola, Vasyl and a maze
Limits: 2 sec., 256 MiB
The Office of «Extralogic» is a real maze. Builders Vasyl and Mykola do not only can’t find a room, they have to paint the door, and got lost!
In order to somehow help the poor builders, the kind employees of «Extralogic» handed an office plan to Mykola and Vasyl. According to the plan, the office consists of \(n\) rooms, some of which are connected by a passage. There are \(n\) such passages. Each passage is bidirectional. It is guaranteed that there is a path between any pair of rooms in the office, and that there is no more than one passage between any pair of rooms in the office.
Mykola and Vasyl remember that they had to draw a door to one of the rooms, which is located in a cycle. A cycle is a sequence of different office rooms \(a_1, a_2, ..., a_k\), that includes a passage between rooms \(a_1\) and \(a_2\), \(a_2\) and \(a_3\), ..., \(a_{k-1}\) and \(a_k\), \(a_k\) and \(a_1\). Help builders find lists of all office rooms that belong in at least one cycle.
Input
First line contains one integer \(n\) – number of rooms in the ofice.
Next \(n\) lines contain two integers \(a_i\) and \(b_i\) – describes \(i\)-th passage between rooms \(a_i\) and \(b_i\).
Output
In first line print one integer \(k\) – number of rooms which belongs to at least one cycle.
In second line print \(k\) integers – indecies of rooms in ascening order.
Constraints
\(30\%\) tests: \(3 \le n \le 100\).
\(70\%\) tests: \(3 \le n \le 10^5\).
For all tests: \(1 \le a_i, b_i \le n\).
Samples
| Input (stdin) | Output (stdout) |
|---|---|
| 4 1 2 2 3 3 4 4 2 | 3 2 3 4 |
Notes
Rooms 2, 3 and 4 belong to a cycle. Room 1 does not belong to any cycle.
Submit a solution
| Element Type | Created | Who | Problem | Compiler | Result | Time (sec.) | Memory (MiB) | # | Actions |
|---|
Коля, Вася і лабіринт - Розбір
У зв’язному графі з \(n\) вершинами та \(n\) ребрами рівно один цикл: дерево має \(n - 1\) ребро, а одне зайве ребро утворює єдиний цикл. Потрібно знайти вершини цього циклу.
Простий спосіб — обрізати «листки». Поки існує вершина степеня \(1\), видаляємо її разом з ребром (зменшуючи степінь її сусіда). Вершини поза циклом утворюють дерева, що «висять» на циклі, тому всі вони будуть видалені, а вершини циклу — ні, бо в кожної з них завжди залишається принаймні два сусіди на циклі. Видалення зручно робити чергою, як у пошуку в ширину. Вершини, що залишилися, і є відповіддю; вони вже йдуть у порядку зростання, якщо переглянути їх за номерами.
В авторському розв’язку цикл шукається пошуком у глибину: перше знайдене ребро до вершини, яка зараз у стеку обходу, замикає цикл, і при поверненні з рекурсії до вершини, з якої цикл почався, збираються всі вершини циклу. Цей спосіб теж працює за \(O(n)\), але глибина рекурсії може сягати \(10^5\).
| Element Type | Created | Who | Problem | Compiler | Result | Time (sec.) | Memory (MiB) | # | Actions |
|---|