Minimum sprinklers required to water a rectangular park
Given N * M rectangular park having N rows and M columns, each cell of the park is a square of unit area and boundaries between the cells is called hex and a sprinkler can be placed in the middle of the hex. The task is to find the minimum number of sprinklers required to water the entire park.
Examples:
Input: N = 3 M = 3
Output: 5
Explanation:
For the first two columns 3 sprinklers are required and for last column we are bound to use 2 sprinklers to water the last column.
Input: N = 5 M = 3
Output: 8
Explanation:
For the first two columns 5 sprinklers are required and for last column we are bound to use 3 sprinklers to water the last column.
Approach:
- After making some observation one thing can be point out i.e for every two column, N sprinkler are required because we can placed them in between of two columns.
- If M is even, then clearly N* (M / 2) sprinklers are required.
- But if M is odd then solution for M – 1 column can be computed using even column formula, and for last column add ( N + 1) / 2 sprinkler to water the last column irrespective of N is odd or even.
C++
#include <iostream>
using namespace std;
typedef long long int ll;
void solve( int N, int M)
{
ll ans = (N) * (M / 2);
if (M % 2 == 1) {
ans += (N + 1) / 2;
}
cout << ans << endl;
}
int main()
{
int N, M;
N = 5;
M = 3;
solve(N, M);
}
|
Java
class GFG{
public static int solve( int n, int m)
{
int ans = n * (m / 2 );
if (m % 2 == 1 )
{
ans += (n + 1 ) / 2 ;
}
return ans;
}
public static void main(String args[])
{
int N = 5 ;
int M = 3 ;
System.out.println(solve(N, M));
}
}
|
Python3
def solve(N, M) :
ans = int ((N) * int (M / 2 ))
if (M % 2 = = 1 ):
ans + = int ((N + 1 ) / 2 )
print (ans)
N = 5
M = 3
solve(N, M)
|
C#
using System;
class GFG{
public static int solve( int n, int m)
{
int ans = n * (m / 2);
if (m % 2 == 1)
{
ans += (n + 1) / 2;
}
return ans;
}
public static void Main(String []args)
{
int N = 5;
int M = 3;
Console.WriteLine(solve(N, M));
}
}
|
Javascript
<script>
function solve(N, M)
{
var ans = (N) * parseInt((M / 2));
if (M % 2 == 1) {
ans += parseInt((N + 1) / 2);
}
document.write(ans);
}
var N, M;
N = 5;
M = 3;
solve(N, M);
</script>
|
Output:
8
Time complexity: O(1)
Auxiliary space: O(1)
Last Updated :
25 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...