pta甲级1010

题目中只说明了给出的字符是在0~35的,并没有说明数的进制也是在0~35的。

想当然的认为两个数的进制都是在这个范围,并没有想到还需要二分范围。另外在运算过程中容易爆long long,需要注意判断。

#include <bits/stdc++.h>
#define ll long long

using namespace std;
int mina, minb;
string a, b;
map<char, int> mp;
ll func(ll x)
{
    ll res=0;
    for(int i=0; b[i]; i++){
        res*=x;
        res+=mp[b[i]];
    }
    if(res<0) res=1e18;
    return res;
}
int main()
{
    for(int i='0'; i<='9'; i++)
        mp[(char)i]=i-'0';
    for(int i='a'; i<='z'; i++)
        mp[(char)i]=i-'a'+10;
    int tag, radix;
    cin>>a>>b>>tag>>radix;
    //scanf("%s %s %d %d", a, b, &tag, &radix);
    if(tag==2) swap(a, b);
    ll na=0;
    for(int i=0; a[i]; i++){
        mina=max(mina, mp[a[i]]);
        na*=radix;
        na+=mp[a[i]];
    }
    for(int i=0; b[i]; i++)
        minb=max(minb, mp[b[i]]);
    ll l=minb+1, r=na, mid;
    while(l<r){
        mid=(l+r)>>1;
        if(func(mid)>=na)
            r=mid;
        else
            l=mid+1;
    }
    if(func(l)==na)
        printf("%lld\n", l);
    else
        puts("Impossible");
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/canchan/p/12238827.html