给定大小为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
Javascript
输出:
6
时间复杂度: O(1)
辅助空间: O(1)