「Codeforces」758D(贪心细节/dp)

题意:原题在这

 

Alexander is learning how to convert numbers from the decimal system to any other, however, he doesn't know English letters, so he writes any number only as a decimal number, it means that instead of the letter A he will write the number 10. Thus, by converting the number 475from decimal to hexadecimal system, he gets 11311 (475 = 1·162 + 13·161 + 11·160). Alexander lived calmly until he tried to convert the number back to the decimal number system.

Alexander remembers that he worked with little numbers so he asks to find the minimum decimal number so that by converting it to the system with the base n he will get the number k.

给定一个进制数及该进制下的串,求十进制下的该数

 

做法:(详见行内注释)

数串从后向前扫,如果某位及之前的十进制和小于给定进制则可以选,直至超过给定进制(贪心)

注意特判0的情况

 

代码:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define maxn 100000005
#define ll unsigned long long
using namespace std;
const ll inf=0x7FFFFFFFFFFFFFFFLL;

char c[65];
ll dp[65];
string s;
int n;

int main()
{
    cin>>n>>s;
    int len=s.size();
    ll ans=0,cnt=1;
    for(int i=len-1;i>=0;)
    {
        ll flag=1,digit=0,now=0,pw=1;
        for(int j=i;j>=0;)
        {
            ll k=(s[j]-'0');//s[i]-'0'表示将串的i位转为数字
            if(now+k*pw<n&&now+k*pw>=0)//如果某位及之前的十进制和小于给定进制
            {
                now+=k*pw,pw*=10;//可以选
                j--,digit++;//选完之后继续向前扫
                if(j<0)//j<0时退出
                {
                    ans+=cnt*now;
                    cout<<ans<<endl;
                    return 0;
                }
            }
            else if(now+k*pw>=n||now+k*pw<0)//如果不能选(特判)
            {
                while(s[j+1]=='0'&&digit!=1)//如果下一位是0且当前位下选过
                {
                    j++;
                    digit--;
                }
                pw/=10;
                i=j,flag=0;
                break;
            }
        }
        ans+=now*cnt;
        cnt*=n;
    }
    cout<<ans<<endl;
    return 0;
}

附上dp方法核心代码:

for (int i=1;i<=len;i++) c[i]=s[i-1];
for (int i=0;i<=len;i++) dp[i]=inf;
dp[0]=0;
for (int i=1;i<=len;i++)
{
    for (int j=i;j<=len;j++)
    {
        now=now*10+c[j]-'0';
        if (now>=n) break;//贪心求比n小的最大值 
        if (c[i]=='0'&& j>i) break;//判断中间的零 
        dp[j]=min(dp[j],dp[i-1]*n+now);
        for (int m=1;m<=len;m++) 
        {
            cout<<dp[m]<<' ';
        }
    }
    cout<<endl;
}
cout<<dp[len]<<endl;

 

转载于:https://www.cnblogs.com/LocaEtric/p/9614980.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值