「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;

猜你喜欢

转载自www.cnblogs.com/LocaEtric/p/9614980.html