CodeForces - 758D Ability To Convert(贪心)

68 篇文章 0 订阅
31 篇文章 0 订阅

Ability To Convert

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



题意:给出n进制和一个对应的n进制的数,问最小换成多大的十进制数
思路:最优的策略肯定是贪心使得低次方的系数尽可能的大。那么逆序遍历就好了。注意有0的时候
例如 1000 1000,对于这种,第一个0用掉一个次方,然后100用掉一个次方,结果为100000
1000 1001,对于这种,第一个1用掉一个次方,然后100用掉一个次方,结果为100001
1000 10000,对于这种,第一个0用掉一个次方,第二个0用掉一个次方,然后100用掉一个次方,结果为100000000

也就是说,(一连串0大于n的位数时)一个0要用掉一个次方,直到一连串0小于n的位数

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

typedef long long LL;
char s[110];
LL n;

LL pow(LL a,LL b)
{
    LL r=1,c=a;
    while(b)
    {
        if(b&1)
            r*=c;
        c*=c;
        b>>=1;
    }
    return r;
}

int main()
{
    scanf("%I64d",&n);
    LL num=0,tmp=n;
    while(tmp)
    {
        tmp/=10;
        ++num;
    }
    scanf("%s",s);
    LL len=strlen(s);
    LL tot=0,ans=0,cnt=0;
    for(LL i=len-1; ~i; )
    {
        LL flag=i,k=0;
        while((tot+(s[i]-'0')*pow(10,k))<n&&(k+1)<=num&&i>=0)//(k+1)相当于当前数的位数
        {
            tot+=(s[i]-'0')*pow(10,k);
            ++k,--i;
        }
        ans+=tot*pow(n,cnt);
        if(s[i+1]=='0')//注意是i+1,因为上面--i了
        {
            while(s[i+1]=='0'&&(i+1)<flag)//最少要用掉一个0
                ++i;
        }
        tot=0,++cnt;
    }
    ans+=tot*pow(n,cnt);
    printf("%I64d\n",ans);
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值