Seoul Subway Line 2
InterviewTime limit2sMemory limit512 MB
Given a connected graph with N vertices and N edges (exactly one cycle), find each vertex's distance to the unique cycle.
- Level
Medium6 of 10
- Topics
- Graph, BFS, Implementation, Queue
- Solved
- No attempts yet
Problem
Seoul Subway Line 2 looks like this.

Line 2 has 51 stations and 51 segments connecting pairs of stations. In other words, it can be represented as a graph with 51 vertices and 51 bidirectional edges. Line 2 consists of one circular line and two branches. A route on which, starting from some station and continuing onward, you can always return to the starting station is called a circular line. A branch is a tree-shaped route that begins at a station belonging to the circular line.
The distance between two stations (vertices) is the number of segments (edges) you must pass through. The distance between station A and the circular line is the minimum distance between A and a station belonging to the circular line.
Given a route map of the same shape as Line 2, find the distance between each station and the circular line.
Input
The first line gives the number of stations N (3 ≤ N ≤ 3,000). Each of the next N lines gives information about a segment connecting two stations. The same segment is never given more than once, and stations are numbered from 1 to N. Only routes in which a path always exists between any two stations are given as input.
Output
Print N integers in total. Print the distance between station 1 and the circular line, the distance between station 2 and the circular line, ..., the distance between station N and the circular line, separated by spaces.