给定尺寸为MxN的地板和尺寸为2×1的瓷砖,任务是找到覆盖MxN尺寸的地板所需的最大瓷砖数量。
注意:瓷砖可以水平或垂直放置,并且任何两个瓷砖都不应重叠。
例子:
Input: M = 2, N = 4
Output: 4
Explanation:
4 tiles are needed to cover the floor.
Input: M = 3, N = 3
Output: 4
Explanation:
4 tiles are needed to cover the floor.
方法:
- 如果N为偶数,则任务是放置m行(N / 2)数量的图块以覆盖整个地板。
- 否则,如果N为奇数,则以与上述要点相同的方式覆盖M行,直到N – 1 (偶数)列,并在最后一列中放入(M / 2)个图块。如果M和N均为奇数,则地板的一个单元仍然未被覆盖。
- 因此,瓷砖的最大数量为floor((M * N)/ 2) 。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the maximum number
// of tiles required to cover the floor
// of size m x n using 2 x 1 size tiles
void maximumTiles(int n, int m)
{
// Print the answer
cout << (m * n) / 2 << endl;
}
// Driver Code
int main()
{
// Given M and N
int M = 3;
int N = 4;
// Function Call
maximumTiles(N, M);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to find the maximum number
// of tiles required to cover the floor
// of size m x n using 2 x 1 size tiles
static void maximumTiles(int n, int m)
{
// Print the answer
System.out.println((m * n) / 2);
}
// Driver code
public static void main (String[] args)
{
// Given M and N
int M = 3;
int N = 4;
// Function call
maximumTiles(N, M);
}
}
// This code is contributed by offbeat
Python3
# Python3 program for the above approach
# Function to find the maximum number
# of tiles required to cover the floor
# of size m x n using 2 x 1 size tiles
def maximumTiles(n, m):
# Prthe answer
print(int((m * n) / 2));
# Driver code
if __name__ == '__main__':
# Given M and N
M = 3;
N = 4;
# Function call
maximumTiles(N, M);
# This code is contributed by sapnasingh4991
C#
// C# program for the above approach
using System;
class GFG{
// Function to find the maximum number
// of tiles required to cover the floor
// of size m x n using 2 x 1 size tiles
static void maximumTiles(int n, int m)
{
// Print the answer
Console.WriteLine((m * n) / 2);
}
// Driver code
public static void Main(String[] args)
{
// Given M and N
int M = 3;
int N = 4;
// Function call
maximumTiles(N, M);
}
}
// This code is contributed by amal kumar choubey
输出:
6
时间复杂度: O(1)
辅助空间: O(1)