这个问题看起来有点挑战性,题目大意是说,给定一组数w_i,每个数代表一个重量是2的w_i次方的哑铃。每次步骤中,我们可以扔掉一些哑铃,条件是它们的总和必须是某个2的x次方。我们需要找到最少的步骤次数,将所有的哑铃处理完。 那问题转化为,如何将这些w_i分组,使得每组的总和对应的二进制合并后的幂数满足条件。例如,如果有多个相同数值的w_i,比如两个1,那么它们的和是2^1 + 2^1 = 2^2。所以这两个可以合并成一个更大的幂,从而可能减少步骤数。 接下来…算了,不废话了, 上代码!(各位也是为此而来吧)
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr);
int n;
cin >> n;
vector<int> w(n);
for (int i = 0; i < n; ++i) {
cin >> w[i];
}
if (n == 0) {
cout << 0 << '\n';
return 0;
}
int initial_max = *max_element(w.begin(), w.end());
vector<int> cnt(initial_max + 2, 0);
for (int x : w) {
cnt[x]++;
}
int max_w = initial_max;
for (int current_w = 0; current_w <= max_w; ++current_w) {
int c = cnt[current_w];
if (c == 0) continue;
int carry = c / 2;
int remainder = c % 2;
cnt[current_w] = remainder;
if (carry > 0) {
if (current_w + 1 >= cnt.size()) {
cnt.resize(current_w + 2 + 1, 0);
}
cnt[current_w + 1] += carry;
if (current_w + 1 > max_w) {
max_w = current_w + 1;
}
}
}
int ans = 0;
for (int x : cnt) {
ans += x;
}
cout << ans << '\n';
return 0;
}