Codeforces Round #171 (Div. 2) - E - Beautiful Decomposition( 贪心 )

题目链接:点击进入

题目

在这里插入图片描述

题意

给你一串值为 n 的二进制串,一个加数可以是 ( + / - ) 2 ^ k ( k >= 0 ) ,求最少的加数凑成 n ( 没有前导零 )

思路

若这个串只有一个1,显然只需要一次即可;
否则,我们可以用减法来求得这个数,例如:11010 = 100000 + 00010 - 01000
反过来就是 11010 - 00010 + 01000 = 100000 ,也就是用最小的加数使原数(x位)变成2^x( 若原数是11…就是变成2 ^ x,若原数是10…就是变成 2 ^ ( x - 1 ),因为10…变成 2 ^ ( x - 1 )比10…变成 2 ^ x要少一步 )
若这一位是1,同时下一位是0,就减去这个1,代价1;
若这一位是1,同时从这一位开始连续m>=2位都是1,那么就是将这位+1,这样这连续的m位1都会变成0,会在这m位后产生一位进位,代价1。
最后再加上一个目标数 ( 2 ^ x | 2 ^ ( x - 1 ) ) 的代价1。就是最小代价。

代码

//#pragma GCC optimize(3)//O3
//#pragma GCC optimize(2)//O2
#include<iostream>
#include<string>
#include<map>
#include<set>
//#include<unordered_map>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<stack>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<fstream>
#define X first
#define Y second
#define base 233 
#define pb push_back
#define INF 0x3f3f3f3f3f3f3f3f
#define pii pair<int,int>
#define lowbit(x) x & -x
#define inf 0x3f3f3f3f
//#define int long long
//#define double long double
//#define rep(i,x,y) for(register int i = x; i <= y;++i)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const double pai=acos(-1.0);
const int maxn=1e6+10;
const int mod=1e9+7;
const double eps=1e-9;
const int N=5e3+10;
/*--------------------------------------------*/
inline int read()
{
    int k = 0, f = 1 ;
    char c = getchar() ;
    while(!isdigit(c)){if(c == '-') f = -1 ;c = getchar() ;}
    while(isdigit(c)) k = (k << 1) + (k << 3) + c - 48 ,c = getchar() ;
    return k * f ;
}
/*--------------------------------------------*/

int n,ans;
string s;

int main() 
{
//	ios::sync_with_stdio(false);
//	cin.tie(0);cout.tie(0);
	cin>>s;
	int len=s.size();ans=1;
	reverse(s.begin(),s.end());
	for(int i=0;i<=len-2;i++)
	{
		if(s[i]=='1')
		{
			if(s[i+1]=='0')
				ans++;
			else
			{
				int p=i;
				while(s[p]=='1'&&p<=len-1)
					p++;
				ans++;
				if(p==len) break;
				s[p]='1';i=p-1;
			}
		}
	}
	cout<<ans<<endl;
    return 0;
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值