给定两个整数M和N ,任务是找到可放置在M * N网格上的最小2 * 1大小的图块,从而满足以下条件:
- 每个瓦片必须完全覆盖木板的2个正方形。
- 一对瓷砖都不能重叠。
- 每个瓷砖躺椅必须完全放置在木板内部。可以触摸电路板的边缘。
如果无法覆盖整个电路板,请打印-1
Input: N = 2, M = 4
Output: 4
Explanation: 4 tiles of dimension 2 * 1. Place each tile in one column.
Input: N = 3, M = 3
Output: -1
方法:按照以下步骤解决问题
- 如果N是偶数,则可以放置(N / 2)* M瓦片以覆盖整个电路板。
- 如果N为奇数,则为2 * 1个图块,因为长度为奇数,不能表示为2的倍数
下面是上述方法的实现:
C++
// C++ Program to implement
// the above approach
#include
using namespace std;
// Function to count tiles of dimensions
// 2 x 1 that can be placed in a grid of
// dimensions M * N as per given conditions
int numberOfTiles(int N, int M)
{
if (N % 2 == 1) {
return -1;
}
// Number of tiles required
return (N * 1LL * M) / 2;
}
// Driver Code
int main()
{
int N = 2, M = 4;
cout << numberOfTiles(N, M);
return 0;
}
Java
// Java Program to implement
// the above approach
import java.io.*;
class GFG {
// Function to count tiles of dimensions
// 2 x 1 that can be placed in a grid of
// dimensions M * N as per given conditions
static int numberOfTiles(int n, int m)
{
if (n % 2 == 1) {
return -1;
}
// Number of tiles required
return (m * n) / 2;
}
// Driver Code
public static void main(String[] args)
{
int n = 2, m = 4;
System.out.println(
numberOfTiles(n, m));
}
}
Python
# Python Program to implement
# the above approach
# Function to count tiles of dimensions
# 2 x 1 that can be placed in a grid of
# dimensions M * N as per given conditions
def numberOfTiles(N, M):
if (N % 2 == 1):
return -1
# Number of tiles required
return (N * M) // 2
# Driver Code
N = 2
M = 4
print(numberOfTiles(N, M))
# This code is contributed by shubhamsingh10
C#
// C# Program to implement
// the above approach
using System;
public class GFG {
// Function to tiles of size 2 x 1
// find the number of tiles that can
// be placed as per the given conditions
static int numberOfTiles(int n, int m)
{
if (n % 2 == 1) {
return -1;
}
// Number of tiles required
return (m * n) / 2;
}
// Driver Code
static public void Main()
{
int n = 2, m = 4;
Console.WriteLine(
numberOfTiles(n, m));
}
}
输出:
4
时间复杂度: O(1)
辅助空间: O(1)