消减整数(思维+贪心)

104 篇文章 0 订阅

https://ac.nowcoder.com/acm/contest/11163/C


思路很好想..但是bug调了很久。

后往前贪心,当前数最多能取多少个,满足前面的每个数都至少取1个。数是log个,最多30,次数最多30,暴力就好。

主要是代码的处理,先把要每个取一个的部分都先-1了,防止一些边界问题。然后再贪心取。

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=50;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar();	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
LL p[maxn];
int main(void)
{
  LL t;t=read();
  p[0]=1;
  for(LL i=1;i<=40;i++) p[i]=p[i-1]*2;
  while(t--){
    LL H=read();
    if(H==2){
        printf("2\n");
        continue;
    }
    LL ans=1;
    H--;
    for(LL i=30;i>=0;i--){
        if(p[i]>H) continue;
        LL res=0;
        LL temp=H;
        LL cnt=0;

        for(LL j=1;j<=30;j++){///枚举次数
            if(temp-p[i]*j>=(1LL<<i)-1-1 ){

                cnt=max(cnt,j);

            }
            else{
                break;
            }
        }

        if(cnt==0) continue;

        res+=cnt;
        temp-=p[i]*cnt;

        for(LL j=i-1;j>=1;j--){
            temp-=p[j]*1;
            res++;
        }

        for(LL j=i-1;j>=0;j--){
            if(temp>0&&temp>=p[j]){
                res+=temp/p[j],temp%=p[j];
            }
        }
        ans+=res;
        break;
    }
    printf("%lld\n",ans);
  }
return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值