Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ program to find minimum number of locations to place bombs to kill all monsters
Suppose we have two arrays X and H. Both are with N elements, also have another two numbers D and A. Consider in a story, a silver fox is fighting with N monsters. The monsters are standing in a row, coordinate of ith monster is X[i], and its health is H[i]. Silver fox can use bombs to attack monsters. Dropping bomb at location x will damage all monsters within the range of x - D to x + D. Their health will be reduced by A. When all monsters have 0 health left, then the fox wins. We have to find the minimum possible are needed to win.
So, if the input is like D = 3; A = 2; X = [1, 5, 9]; H = [2, 4, 2], then the output will be 2, because first bomb at coordinate 4, new health values are [0, 2, 2], then at position 6 to make all health values [0, 0, 0].
Steps
To solve this, we will follow these steps −
Define a large array q Define an array of x and h pairs n := size of X d := D a := A for initialize i := 1, when i <= n, update (increase i by 1), do: num[i].x := X[i - 1] num[i].h := H[i - 1] sort the array num sum := 0 for initialize i := 1, when i <= n, update (increase i by 1), do: q[i] := q[i] + q[i - 1] num[i].h := num[i].h - q[i] * a if num[i].h <= 0, then: Ignore following part, skip to the next iteration p := (if num[i].h mod a is same as 0, then num[i].h / a, otherwise num[i].h / a + 1) tmp := num[i].x + 2 * d sum := sum + p q[i] := q[i] + p l := i, r = n while l < r, do: mid := (l + r + 1) / 2 if num[mid].x <= tmp, then: l := mid Otherwise r := mid - 1 q[l + 1] - = p return sum
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 20;
int n;
int d, a, q[maxn];
struct node{
int x, h;
bool operator<(const node& a) const{
return x < a.x;
}
} num[maxn];
int solve(int D, int A, vector<int> X, vector<int> H){
n = X.size();
d = D;
a = A;
for (int i = 1; i <= n; i++){
num[i].x = X[i - 1];
num[i].h = H[i - 1];
}
sort(num + 1, num + n + 1);
int sum = 0;
for (int i = 1; i <= n; i++){
q[i] += q[i - 1];
num[i].h -= q[i] * a;
if (num[i].h <= 0)
continue;
int p = (num[i].h % a == 0 ? num[i].h / a : num[i].h / a + 1);
int tmp = num[i].x + 2 * d;
sum += p;
q[i] += p;
int l = i, r = n;
while (l < r){
int mid = (l + r + 1) >> 1;
if (num[mid].x <= tmp)
l = mid;
else
r = mid - 1;
}
q[l + 1] -= p;
}
return sum;
}
int main(){
int D = 3;
int A = 2;
vector<int> X = { 1, 5, 9 };
vector<int> H = { 2, 4, 2 };
cout << solve(D, A, X, H) << endl;
}
Input
3, 2, { 1, 5, 9 }, { 2, 4, 2 }
Output
2