BZOJ 4029 HEOI2015 定价 数位贪心

本文提供了一种高效的算法来查找给定区间内荒谬程度最小的数字,通过从高位到低位的贪心策略进行优化。

题目大意:定义一个数的荒谬程度为去掉末尾所有0后的数字数量2(若末尾为5则荒谬程度减掉1),求[l,r]区间内荒谬程度最小的数字(若多个相同取最小)
从高位往低位贪心即可。
注意500的荒谬程度比100低

#include <assert.h>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int Calculate(long long l,long long r)
{
    long long temp,ans=0;
    for(temp=1;temp<=l;temp*=10);
    if(temp/2>=l&&temp/2<=r)
        return temp/2;
    if(temp*5<=r)
        return temp*5;
    temp/=10;
    for(;temp;temp/=10)
    {
        long long target;

        target=l-l%temp+(bool)(l%temp)*temp; 
        if( r>=target )
            return ans+target;

        if(l%temp<=temp/2)
        {
            target=l-l%temp+temp/2;
            if(r>=target)
                return ans+target;
        }
        ans+=l-l%temp;
        l%=temp;r%=temp;
    }
    assert(false);
}
int main()
{
    //freopen("4029.in","r",stdin);
    //freopen("4029.out","w",stdout);
    int T,l,r;
    for(cin>>T;T;T--)
    {
        scanf("%d%d",&l,&r);
        printf("%d\n",Calculate(l,r));
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值