跳到正文

题解

题解:CF2118C Make It Beautiful

CommandSR约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年6月27日
收录
2025年12月12日
更新
2026年10月13日
篇幅
约 2 分钟
获赞
2
题目
CF2118C

版本

  1. v1当前

基本思路

计算每个值 popcount 可以增加 11 的最小值,记作 calcicalc_i,即从低到高找到第一个 00,变成 11。

如 calc6=7calc_6 = 7, calc7=15calc_7 = 15。

被每一个 calcicalc_i 值丢进优先队列,贪心寻找代价最小的计入答案即可。

Code

C++
#include <bits/stdc++.h>
#define int long long
#define ll long long
#define F(i, a, b) for (int i = a; i <= b; ++i)
#define _F(i, a, b) for (int i = a; i >= b; --i)
using namespace std;
const int N = 5005;
ll n, m, a[N];
struct S {
	ll x, y;
	friend bool operator < (S u, S v) {
		return u.y - u.x > v.y - v.x;
	}
};
priority_queue <S> q;
ll calc(ll x) {
	F(i, 0, 60) {
		if (!(x & (1ll<<i))) {
			ll y = x ^ (1ll<<i);
			return y;
		}
	}
	return 114514; // 不可能返回这个
}
void Solve() {
	while (!q.empty()) q.pop();
	cin >> n >> m;
	ll ans = 0;
	F(i, 1, n) {
		cin >> a[i];
		q.push((S){a[i], calc(a[i])});
		ans += __builtin_popcount(a[i]);
	}
	ll cur = 0;
	while (!q.empty() && cur <= m) {
		S u = q.top(); q.pop();
		ll po = u.y - u.x;
		if (cur + po <= m) {
			cur += po;
			++ans;
			q.push((S){u.y, calc(u.y)});
		} else {
			break;
		}
	}
	cout << ans << '\n';
}
signed main() {
	ll T; cin >> T; 
	while (T--) Solve();
	return 0;
}
原文