codeforces 758D. Ability To Convert

time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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 475 from 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.

Input

The first line contains the integer n (2 ≤ n ≤ 109). The second line contains the integer k (0 ≤ k < 1060), it is guaranteed that the number k contains no more than 60 symbols. All digits in the second line are strictly less than n.

Alexander guarantees that the answer exists and does not exceed 1018.

The number k doesn't contain leading zeros.

Output

Print the number x (0 ≤ x ≤ 1018) — the answer to the problem.

Examples
Input
13
12
Output
12
Input
16
11311
Output
475
Input
20
999
Output
3789
Input
17
2016
Output
594
Note

In the first example 12 could be obtained by converting two numbers to the system with base 13: 12 = 12·130 or 15 = 1·131 + 2·130.

给定数的进制和对应进制下的数,并且由于不使用英文字母,所转化成的十进制数有多种,请问其中最小的是哪一种。

简单的dp,设f[i][j]表示前i个数到n的j次方所能得到的最小数,由于我们看到如果从前往后开头的是n的几次方不确定,所以将这个数反向存储,使得n的次方递增。

f[i][j]=min(f[k][j-1]+a(k+1,i)*n^j);a(k+1,i)<n&&1<=k<i a(k+1,i)表示的是k+1到i的数字大小,这个在求的时候,首先等于x[i],然后每次乘10加上x[k]即可(x[i]表示对应位置的值)

对于第i位为0的要做特殊处理,直接让f[i][j]=f[i-1][j-1];

#include<cstdio>
#include<cstring>
typedef long long ll;
const ll INF=1000000000000000001;
ll f[65][65];
char c[65];
int x[65];
ll my_min(ll a,ll b)
{
    return a<b?a:b;
}
int main()
{
    int n,xd=0;
    ll ans=INF;
    scanf("%d%s",&n,c);
    int l=strlen(c);
    for(int i=0;i<l;++i) x[l-i]=c[i]-'0';
    for(int i=1;i<=l;++i)
        for(int j=0;j<l;++j)
            f[i][j]=INF;//赋初值
    f[1][0]=x[1];
    for(ll i=1;i<INF&&i>0;i*=n,++xd);//保证答案小于1e18
    for(int i=2;i<=l;++i)
    {
        ll t=n,tt;
        if(!x[i])
        {
            for(int j=1;j<i&&j<l&&t>0;++j,t*=n) f[i][j]=f[i-1][j-1];
            continue;
        }
        for(int j=1;j<i&&j<xd;++j,t*=n)
        {
            tt=x[i];
            for(int k=i-1;k>0&&tt<n;tt=tt*10+x[k],--k)
                if(f[k][j-1]<INF&&f[k][j-1]+tt*t>=0) f[i][j]=my_min(f[i][j],f[k][j-1]+tt*t);
        }
        if(tt<n) f[i][0]=tt;//能够只有一位
    }
    for(int i=0;i<l;++i) ans=my_min(ans,f[l][i]);
    printf("%lld",ans);
    return 0;
}
原文地址:https://www.cnblogs.com/bzmd/p/6352221.html