「杂题乱刷」CF1977B

题目链接

CF1977B (luogu)

CF1977B (codeforces)

解题思路

考虑通用做法。

我们发现如果直接用二进制来表示的话这个数会只包含 \(0,1\) 这两个数字。

发现这时阻碍我们构造的是连续的数字 \(1\)

考虑消除连续的数字 \(1\)

容易发现连续的数字 \(1\) 可以转化成将这一段最高位的数字 \(1\) 的下一位进位,并将这一段最低位的数字 \(1\) 退位的操作。

容易证明这样构造一定两两之间不会冲突。

参考代码

#include<bits/stdc++.h>
using namespace std;
//#define map unordered_map
#define forl(i,a,b) for(register long long i=a;i<=b;i++)
#define forr(i,a,b) for(register long long i=a;i>=b;i--)
#define forll(i,a,b,c) for(register long long i=a;i<=b;i+=c)
#define forrr(i,a,b,c) for(register long long i=a;i>=b;i-=c)
#define lc(x) x<<1
#define rc(x) x<<1|1
#define mid ((l+r)>>1)
#define cin(x) scanf("%lld",&x)
#define cout(x) printf("%lld",x)
#define lowbit(x) (x&-x)
#define pb push_back
#define pf push_front
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define endl '\n'
#define QwQ return 0;
#define ll long long
#define ull unsigned long long
#define lcm(x,y) x/__gcd(x,y)*y
#define Sum(x,y) 1ll*(x+y)*(y-x+1)/2
#define aty cout<<"Yes\n";
#define atn cout<<"No\n";
#define cfy cout<<"YES\n";
#define cfn cout<<"NO\n";
#define xxy cout<<"yes\n";
#define xxn cout<<"no\n";
#define printcf(x) x?cout<<"YES\n":cout<<"NO\n";
#define printat(x) x?cout<<"Yes\n":cout<<"No\n";
#define printxx(x) x?cout<<"yes\n":cout<<"no\n";
ll t;
ll n;
ll ans[40],k,ans2[40],sum;
void solve()
{
	cin>>n;
	sum=0,k=0;
	ll lst=n;
	while(lst)
		ans[++k]=lst%2,lst/=2;
	/*
	19:10011-> 11001  -1 0 1 0 1
	*/
	forl(i,1,k+1)
	{
		if(ans[i]==2)
			ans[i]=0,ans[i+1]++;
		if(ans[i]==1)
			sum++;
		else
		{
			if(sum>=2)
			{
				ans[i]++;
				forr(j,i-1,i-sum)
					ans[j]=0;
				ans[i-sum]=-1;
			}
			sum=ans[i]==1;
		}
	}
	k+=ans[k+1]==1;
	cout<<k<<endl;
	forl(i,1,k)
		cout<<ans[i]<<' ',ans[i]=0;
	ans[k+1]=0;
	cout<<endl;
}
int main()
{
	IOS;
	t=1;
	cin>>t;
	while(t--)
		solve();
	QwQ;
}
posted @ 2024-05-28 21:14  wangmarui  阅读(3)  评论(0编辑  收藏  举报