C++程式找出擊敗敵人的最小操作次數
假設,我們正在玩一個電子遊戲,遊戲主角使用刀來擊敗敵人。主角可以使用刀來砍殺敵人,或者可以將刀扔向敵人。如果主角扔出一把刀,那麼這把刀將無法再次取回。刀i造成的傷害在陣列'knives'中給出,其中每個元素的格式為{slash, throw}。'Slash'表示用該刀砍殺敵人造成的傷害,'throw'表示用該刀投擲敵人造成的傷害。砍殺可以無限次進行,但每把刀只能投擲一次。現在,出現了一個生命值為h的敵人。我們需要找出擊敗敵人所需的最小操作次數(砍殺或投擲)。當敵人的生命值變為0時,敵人就被擊敗。
因此,如果輸入類似於n = 2,h = 11,knives = {{4, 5}, {3, 6}},則輸出為2。
如果主角投擲兩把刀,則造成的傷害為5 + 6 = 11。敵人的生命值變為0,因此他們被擊敗。
步驟
為了解決這個問題,我們將遵循以下步驟:
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))))
示例
讓我們看看以下實現以更好地理解:
#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; }
輸入
2, 11, {{4, 5}, {3, 6}}
輸出
2
廣告