计算网格中的单元格,通过K垂直或水平跳跃可以达到最大数量的单元格。
- 最后更新 : 2021年8月6日
给定一个尺寸为N*M的矩阵 mat[][]和一个正整数K,任务是找出网格中的单元格数量,通过垂直或水平方向的K次跳跃,可以达到最大的单元格数量。
例子。
**输入。**N = 3, M = 3, K = 2
输出。4
解释:
以X表示的单元格是可以通过K (=2)次跳跃到达的最大单元格(=2):
X O X
OO O
X O X**输入。**N = 5, M = 5, K = 2
**输出。**9
**办法。**根据以下观察,可以通过分别计算行和列的可能单元格数量来解决给定问题。
- 考虑任何一行,比如说i ,使i<=K,那么从i开始用K的跳转可以到达的行数是(N**-i)/K+1。**
- 如果行说i是**i>K,**那么这些单元格与一些X <=K的行相连,因此它们已经被考虑了。
因此,从上面的观察来看,我们的想法是找到与某一变量中最大行数相连的行数,例如count_R。同样地,对于列,找出与某一变量中最大列数相连的列数,例如count_C。
现在,网格中的单元格数量,即最大的单元格在垂直或水平方向上跳过K后可以到达的单元格数量,由**(count_R)*(count_C)**给出。
下面是上述方法的实现。
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;// Function to count the number of cells// in the grid such that maximum cell is// reachable with a jump of Klong long countCells(int n,int m,int s){// Maximum reachable rows// from the current rowint mx1 = -1;// Stores the count of cell that are// reachable from the current rowint cont1 = 0;for (int i = 0; i < s && i < n; ++i) {// Count of reachable rowsint aux = (n - (i + 1)) / s + 1;// Update the maximum valueif (aux > mx1) {mx1 = cont1 = aux;}// Add it to the countelse if (aux == mx1)cont1 += aux;}// Maximum reachable columns from// the current columnint mx2 = -1;// Stores the count of cell that are// reachable from the current columnint cont2 = 0;for (int i = 0; i < s && i < m; ++i) {// Count of rechable columnsint aux = (m - (i + 1)) / s + 1;// Update the maximum valueif (aux > mx2)mx2 = cont2 = aux;// Add it to the countelse if (aux == mx2)cont2 += aux;}// Return the total count of cellsreturn (long long)(cont1 * cont2);}// Driver Codeint main(){int N = 5, M = 5, K = 2;cout << countCells(N, M, K);return 0;} |
Python3
# Python 3 program for the above approach# Function to count the number of cells# in the grid such that maximum cell is# reachable with a jump of Kdef countCells(n, m, s):# Maximum reachable rows# from the current rowmx1= -1# Stores the count of cell that are# reachable from the current rowcont1= 0i= 0while(i < sand i < n):# Count of reachable rowsaux= (n- (i+ 1))// s+ 1# Update the maximum valueif (aux > mx1):mx1= cont1= aux# Add it to the countelif(aux== mx1):cont1+= auxi+= 1# Maximum reachable columns from# the current columnmx2= -1# Stores the count of cell that are# reachable from the current columncont2= 0i= 0while(i < sand i < m):# Count of rechable columnsaux= (m- (i+ 1))// s+ 1# Update the maximum valueif (aux > mx2):mx2= cont2= aux# Add it to the countelif(aux== mx2):cont2+= auxi+= 1# Return the total count of cellsreturn cont1* cont2# Driver Codeif __name__== '__main__':N= 5M= 5K= 2print(countCells(N, M, K))# This code is contributed by ipg2016107 |
输出。
9
**时间复杂度。**O(N + M)
辅助空间。O(1)
读者请注意!现在不要停止学习。掌握竞争性编程的所有重要数学概念。 CP课程的基本数学以适合学生的价格获得所有重要的数学概念。要完成从学习语言到DS Algo以及更多的准备工作,请参考 完整的面试准备课程.
我的个人笔记 箭头_下降_上升
保存