#P12418. Minimum Subway Lines
Minimum Subway Lines
Minimum Subway Lines
S City plans to construct an underground subway network to ease above-ground traffic congestion. The underground network consists of \(n\) horizontal tunnels and \(m\) vertical tunnels. Subway stations are built at the intersections of these tunnels, making a total of \(n \times m\) stations.
To ensure full coverage, every station must be served by at least one subway line. Note that each subway line runs along a single horizontal tunnel or a single vertical tunnel without turning (i.e. no bending is allowed). Moreover, the overall network must be connected; that is, starting from any station, one must be able to reach any other station by taking one or more subway lines (transferring between lines is allowed where lines intersect).
Your task is to determine the minimum number of subway lines needed to cover all \(n \times m\) stations while satisfying the connectivity requirement.
Observation:
- A subway line along a horizontal tunnel covers all stations in that row, and a vertical subway line covers all stations in that column.
- If only lines of the same orientation (all horizontal or all vertical) are used and there is more than one of them, they do not intersect (hence the network is disconnected). Thus, at least one line of each orientation is required unless there is only one row or one column.
- For \(n,m>1\), one optimal strategy is to choose all lines in the smaller dimension and one line in the other dimension. Therefore, the answer is \(\min(n, m) + 1\).
- For the edge case where either \(n = 1\) or \(m = 1\), a single subway line (covering the only row or column) is sufficient.
In summary, the minimum number of subway lines required is given by:
[ \text{answer} = \begin{cases} 1, & \text{if } n = 1 \text{ or } m = 1, \ \min(n, m) + 1, & \text{if } n > 1 \text{ and } m > 1. \end{cases} ]
inputFormat
The input consists of a single line containing two positive integers \(n\) and \(m\) (\(1 \leq n, m \leq 10^9\)), representing the number of horizontal and vertical tunnels respectively.
Note: When \(n = 1\) or \(m = 1\), the subway network consists of a single row or column and only one subway line is needed.
outputFormat
Output a single integer indicating the minimum number of subway lines required.
sample
1 1
1