This problem was posted by HackerRank
Army Game
Luke is daydreaming in Math class. He has a sheet of graph paper with rows and columns, and he imagines that there is an army base in each cell for a total of n * m bases. He wants to drop supplies at strategic points on the sheet, marking each drop point with a red dot. If a base contains at least one package inside or on top of its border fence, then it's considered to be supplied. For example:

Given n and m, what's the minimum number of packages that Luke must drop to supply all of his bases?
Input Format
Two space-separated integers describing the respective values n and m
Output Format
Print a single integer denoting the minimum number of supply packages Luke must drop.
Sample Input 0
2 2
Sample Output 0
1
Explanation 0
Luke has four bases in a 2 x 2 grid. If he drops a single package where the walls of all four bases intersect, then those four cells can access the package:

Because he managed to supply all four bases with a single supply drop, we print 1 as our answer.
Solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using namespace std; | |
int CalcDropped(int n,int m) | |
{ | |
int extraCells=0, dropped=0; | |
extraCells = (n-m) * m; | |
dropped = m*m /4; | |
dropped = dropped + (extraCells / 4) + ((extraCells)%4)/2; | |
return dropped; | |
} | |
int main() | |
{ | |
int n=0, m=0; | |
cin >> n >> m; | |
int dropped=0, extraCells=0; | |
if ((n==1) || (m==1)){ | |
if(n * m % 2){ | |
dropped = ((n*m) / 2) +1; | |
} | |
else{ | |
dropped = (n*m)/2; | |
} | |
} | |
else{ | |
if(n >= m){ | |
dropped = CalcDropped(n,m); | |
} | |
else{ | |
dropped = CalcDropped(m,n); | |
} | |
} | |
cout << dropped; | |
return EXIT_SUCCESS; | |
} |
No comments:
Post a Comment