Change Segment Colors
There is a map with n
segments. Every segment on the map can either be a red segment or a black segment. There is no closed loop in the map (i.e., no cycles). Initially, all segments on the map are red. You need to perform m
operations on the map, and there are two types of operations:
- Given two stations
a
andb
:- For every station
x
on the path froma
tob
(includinga
andb
), change all segments connected tox
to red. - Then convert all the segments on the path from
a
tob
into black.
- For every station
- Given two stations
a
andb
:- Calculate how many black segments exist on the path from
a
tob
.
- Calculate how many black segments exist on the path from
Input Format:
The input is an array of strings:
- The first string contains two integers
n
andm
, wheren
is the number of stations andm
is the number of operations. - The next
n - 1
strings, each containing two integersu
andv
, indicate that there is a segment between stationu
and stationv
. - The next
m
strings each contain integersopi
,ai
, andbi
:opi
represents the operation type:1
means the first type of operation.2
means the second type of operation.
ai
andbi
represent the two stations. Note thatai
is not equal tobi
.
Output Format:
The output is an array of integers. For every second type of operation, output the result as an integer.
Example:
Input:
operations = ["8 5", "1 2", "1 3", "3 4", "4 5", "4 6", "2 8", "2 9", "1 1 6", "1 2 4", "2 1 6", "1 1 5", "2 2 6"]
Output:
[2, 2]
Explanation:
- For the first operation
(1 1 6)
, the path from station 1 to station 6 is changed to black segments. - For the second operation
(1 2 4)
, the path from station 2 to station 4 is changed to black segments. - For the third operation
(2 1 6)
, the number of black segments on the path from station 1 to station 6 is 2. - For the fourth operation
(1 1 5)
, the path from station 1 to station 5 is changed to black segments. - For the fifth operation
(2 2 6)
, the number of black segments on the path from station 2 to station 6 is 2.
This version replaces the LaTeX formatting with simple, structured text to ensure clarity and readability.