To solve this problem, we need to determine the maximum number of cells intersected by at least one line when drawing k lines (horizontal or vertical) on an n x n grid.
Approach
The key insight here is to recognize two main cases:
- Case 1: k ≤ n: If we draw k lines of the same type (all horizontal or all vertical), each line covers n cells, and there are no overlaps. Thus, the total number of intersected cells is k * n.
- Case 2: k > n: Drawing n lines of one type (either all horizontal or all vertical) covers all n² cells in the grid. Adding more lines (beyond n) does not increase the number of intersected cells since all cells are already covered.
The solution is to take the minimum of k * n (from Case 1) and n² (from Case 2), as this gives the maximum possible intersected cells.
Solution Code
n, k = map(int, input().split())
print(min(n * k, n * n))
Explanation
- Case 1: When k ≤ n, the maximum cells intersected are k * n (all lines are of one type, no overlaps).
- Case 2: When k > n, the maximum cells intersected are n² (since n lines of one type cover all cells, and additional lines do not add any new cells).
This approach efficiently computes the result in constant time O(1) as it involves basic arithmetic operations and a minimum check. The solution is optimal and handles all possible values of k (up to 2n, the maximum possible lines in an n x n grid).
Answer: The code will output the correct maximum number of intersected cells as described. For example, if n=3 and k=4, the output is 9 (since 3 lines cover all cells), and if n=3 and k=2, the output is 6 (2 lines each covering 3 cells).
The final answer is the code provided above.
n, k = map(int, input().split())
print(min(n * k, n * n))

作者声明:本文包含人工智能生成内容。