Mô tả bài toán
Có n con dao, dao i gây sát thương slash_i (cắt, không giới hạn lần) và throw_i (ném, 1 lần). Kẻ thù máu h. Tìm số phép (cắt/ném) ít nhất để hạ máu ≤ 0.
Ví dụ
n=2,h=11, knives={{4,5},{3,6}}. Đầu ra: 2 (ném cả 2: 5+6=11).
Thuật toán (Tham lam)
- Tìm
maxSlash = max(slash_i). - Sắp xếp dao theo
throwgiảm dần. - Duyệt dao: nếu
throw_i > maxSlashthì ném (giảmh, tăng đếm). Dừng khihoặcthrow_i ≤ maxSlash. - Nếu
0, dùng dao cắt tốt nhất: thêmceil(h/maxSlash)phép cắt.
Đoạn mã C++
#include <bits/stdc++.h>
using namespace std;
void solve(int n,int h,vector<pair<int,int>> knives){
int maxSlash=0;
for(auto &k:knives) maxSlash=max(maxSlash,k.first);
sort(knives.begin(),knives.end(),
[](auto &a,auto &b){return a.second>b.second;});
int res=0;
for(auto &k:knives){
if(k.second>maxSlash){
h-=k.second; res++;
if(h<=0){ cout<
Đầu vào / Đầu ra
Input: 2, 11, {{4,5},{3,6}}
Output: 2