
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
Minimum Operations Required to Defeat an Enemy in C++
Suppose, we are playing a video game where the protagonist uses knives to defeat his enemies. The protagonist can use the knife for slashing the enemy or he can throw it towards the enemy. If the protagonist throws a knife, that cannot be retrieved again. The damage dealt by knife i is given in the array 'knives' where each element is of the form {slash, throw}. 'Slash' means the damage done to an enemy by slashing them with that knife and 'throw' means damage done to them by throwing that particular knife. Slashing can be done unlimited times, but a knife can only once be thrown. Now, an enemy appears who has health h. We have to find out the minimum number of operations (slashing or throwing) that are necessary to defeat the enemy. The enemy gets defeated when they have 0 health.
So, if the input is like n = 2, h = 11, knives = {{4, 5}, {3, 6}}, then the output will be 2.
If the protagonist throws both knives, the damage dealt is 5 + 6 = 11. The enemy's health becomes 0, so they get defeated.
Steps
To solve this, we will follow these steps −
val := 0 for initialize i := 0, when i < n, update (increase i by 1), do: val := maximum of (val and first value of knives[i]) sort the array knives res := 0 for initialize i := 0, when i < n, update (increase i by 1), do: if second value of knives[i] > val, then: h := h - second value of knives[i] (increase res by 1) if h <= 0, then: print(res) exit Otherwise Come out from the loop print((res + ceiling value of (h / (double))))
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; void solve(int n, int h, vector<pair<int, int>> knives){ int val = 0; for(int i = 0; i < n; i++){ val = max(val, knives[i].first); } sort(knives.begin(), knives.end()); int res = 0; for(int i = 0; i < n; i++){ if(knives[i].second > val){ h -= knives[i].second; res++; if(h <= 0){ cout << res << endl; return; } } else break; } cout << (res + ceil(h / (double)val)) << endl; } int main() { int n = 2, h = 11; vector<pair<int, int>> knives = {{4, 5}, {3, 6}}; solve(n, h, knives); return 0; }
Input
2, 11, {{4, 5}, {3, 6}}
Output
2