Editorial for Lì Xì
Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.
Submitting an official solution before solving the problem yourself is a bannable offence.
\(\color{red}{\text{Spoiler Alert}_{{}_{{}^{{}^{v2.0}}}}}\)
\(\color{red}{\text{Khuyến khích bạn đọc trước khi đọc phần lời giải xin hãy thử code ra thuật của mình dù nó có sai hay đúng}}\)
\(\color{red}{\text{Sau đó từ phần bài giải và thuật toán trước đó mà đối chiếu, rút nhận xét với thuật của mình và thu được bài học (không lãng phí thời gian đâu).}}\)
\(\color{orange}{\text{Hint 1 <Brute-force>}}\)
- Thử từng dãy và kiểm tra nếu thỏa mãn thì chọn kết quả tốt nhất
\(\color{orange}{\text{Hint 2 <Greedy>}}\)
-
Gọi \(cnt\) là số túi mình lấy thêm được nữa và \(sum\) là kết quả cần tìm
-
Ban đầu mình lấy được thêm 1 túi và chưa lấy túi nào nên \(cnt = 1\) và \(sum = 0\)
-
Với mỗi túi có cặp \((a_i, b_i)\)
Nếu \(b_i > 0\) thì mình tăng biến \(cnt = cnt + b_i - 1\) và lấy túi \(i\) nên \(sum = sum + a_i\)
Nếu \(b_i = 0\) thì đưa nó vào một mảng \(x\)
Khi duyệt xong các cặp, ta sẽ duyệt trong mảng \(x\) lấy \(min(cnt, x.size)\) phần tử lớn nhất
\(\color{green}{\text{Preference AC Code }}\): Greedy
\(^{^{\color{purple}{\text{Complexity : }} O(n \log n)\ \color{purple}{\text{time}}\ ||\ O(n)\ \color{purple}{\text{memory}}}}\)
C++
int main()
{
int n = readInt();
int cnt = 1;
int sum = 0;
vector<int> x;
for (int i = 0; i < n; ++i)
{
int a, b;
cin >> a >> b;
if (b > 0)
{
sum += a;
cnt += b - 1;
}
else x.push_back(a);
}
sort(all(x), greater<int>());
cnt = min(cnt, (int)x.size());
for (int i = 0; i < cnt; ++i)
sum += x[i];
cout << sum;
return 0;
}
Comments