跳到正文

题解

题解:P10892 SDOI2024

lkrqwq约 1 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 1 分钟
获赞
1
题目
P10892

版本

  1. v1当前

我们有一个比较显然的贪心策略:在纠结的时候将 nn 变为偶数,这样能尽量减少后面的纠结次数。

那么这道题就做完了,时间复杂度 O(log⁡n)O(\log n)。

代码如下:

C++
#include <iostream>
#include <cmath>
#include <unordered_map>
using namespace std;
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
	int t;
	cin >> t;
	while (t--) {
		long long x;
		cin >> x;
		int cnt = 0;
		while (x > 0) {
			if (x % 2 == 0) x /= 2;
			else {
				++cnt;
				if ((x - 1) / 2 % 2 == 0) {
					x = (x - 1) / 2;
				} else {
					x = (x + 1) / 2;
				}
			}
		}
		cout << cnt << '\n';
	}
}
原文