题解:P10892 SDOI2024

· · 题解

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

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

代码如下:

#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';
    }
}