CF 1864 C

发布时间 2023-09-09 09:31:57作者: 铜锣骚

C. Divisor Chain

看到样例2中的\(5\xrightarrow{-1}4\xrightarrow{-2}2\xrightarrow{-1}1\)想到了是不是应该把\(x\)向着\(2^n\)去凑,凑到了之后通过不断的减去\(2^{n-1}\)最后达到\(1\),然后就可以朝着这个方向去写。

通过不断枚举\(i\)(\(i =i*2\)),遇到取模不为零的情况时将\(x-i/2\),直到\(x=i\)

也可以通过不断减去\(lowbit(x)\)的方式,直到\(lowbit(x)=x\)

这种方法通过观察二进制的性质,能让每一个出现的“除数”最多出现两次,从而过题。

代码

#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
typedef long long ll;
typedef pair<ll, ll> PII;

const int N = 1010;
int t;
int x;


signed main()
{
    std::ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    cin >> t;
    while (t--)
    {
        cin >> x;
        vector<int> ans;
        ans.push_back(x);
        for(int i = 2;i < x;i <<= 1)
        {
            if(x % i)
            {
                x -= (i >> 1);
                ans.push_back(x);
            }
        }
        while(x > 1)
        {
            x /= 2;
            ans.push_back(x);
        }
        int si = ans.size();
        cout << si << endl;
        for(int i = 0;i < si;i++)
        {
            cout << ans[i] << " ";
        }
        cout << endl;
    }

    return 0;
}