Input: power =4, damage =[1,2,3,4], health =[4,5,6,8]Output: 39Explanation:
* Attack enemy 3in the first two seconds, after which enemy 3 will go down, the number of damage points dealt to Bob is`10 + 10 = 20` points.* Attack enemy 2in the next two seconds, after which enemy 2 will go down, the number of damage points dealt to Bob is`6 + 6 = 12` points.* Attack enemy 0in the next second, after which enemy 0 will go down, the number of damage points dealt to Bob is`3` points.* Attack enemy 1in the next two seconds, after which enemy 1 will go down, the number of damage points dealt to Bob is`2 + 2 = 4` points.
Input: power =1, damage =[1,1,1,1], health =[1,2,3,4]Output: 20Explanation:
* Attack enemy 0in the first second, after which enemy 0 will go down, the number of damage points dealt to Bob is`4` points.* Attack enemy 1in the next two seconds, after which enemy 1 will go down, the number of damage points dealt to Bob is`3 + 3 = 6` points.* Attack enemy 2in the next three seconds, after which enemy 2 will go down, the number of damage points dealt to Bob is`2 + 2 + 2 = 6` points.* Attack enemy 3in the next four seconds, after which enemy 3 will go down, the number of damage points dealt to Bob is`1 + 1 + 1 + 1 = 4` points.
To minimize the total damage dealt to Bob, we should always attack the enemy with the highest damage per second first, as killing them earlier reduces the total damage Bob receives. At each second, Bob attacks the alive enemy with the highest damage, reducing their health by power.
classSolution {
public:longlong minimumDamage(int power, vector<int>& damage, vector<int>& health) {
int n = damage.size();
vector<pair<int, int>> enemies;
for (int i =0; i < n; ++i) enemies.emplace_back(damage[i], health[i]);
auto cmp = [](const pair<int,int>& a, const pair<int,int>& b) { return a.first < b.first; };
priority_queue<pair<int,int>, vector<pair<int,int>>, decltype(cmp)> pq(cmp);
for (auto& e : enemies) pq.push(e);
longlong total =0;
while (!pq.empty()) {
longlong curDamage =0;
vector<pair<int,int>> temp;
while (!pq.empty()) {
auto e = pq.top(); pq.pop();
curDamage += e.first;
temp.push_back(e);
}
total += curDamage;
sort(temp.begin(), temp.end(), cmp);
temp[0].second -= power;
vector<pair<int,int>> next;
for (auto& e : temp) if (e.second >0) next.push_back(e);
pq = priority_queue<pair<int,int>, vector<pair<int,int>>, decltype(cmp)>(cmp, next);
}
return total;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
defminimum_damage(power: int, damage: list[int], health: list[int]) -> int:
import heapq
n = len(damage)
alive = [(-damage[i], health[i], i) for i in range(n)]
heapq.heapify(alive)
total =0while alive:
cur_damage = sum(-d for d, h, i in alive)
total += cur_damage
d, h, idx = heapq.heappop(alive)
h -= power
if h >0:
heapq.heappush(alive, (d, h, idx))
return total