pat1010

来源:互联网 发布:淘宝怎么提升排名靠前 编辑:程序博客网 时间:2024/05/19 17:52

radix数值比较大。不能暴力,即使在二分搜索的时候也要注意,radix很大,计算可能会出现负数,那么比大小恰恰得到相反的结果,二分的结果就会Impossible。

#include<cstdio>#include<string>using namespace std;typedef long long ll;ll cton(char c){    if('0'<=c&&c<='9') return c-'0';    else return c-'a'+10;}ll compute(string num,ll radix){    ll sum=0;    for(int i=0;i<num.length();i++){        sum*=radix;        sum+=cton(num[i]);    }    return sum;}int cmp(string num,ll radix,ll s){    ll sum=0;    for(int i=0;i<num.length();i++){        sum*=radix;        if(sum<0) return 1;        sum+=cton(num[i]);        if(sum>s) return 1;    }    return (sum==s)-1;}int main(){    char n[2][15];    int tag;    ll radix;    while(scanf("%s%s%d%lld",n[0],n[1],&tag,&radix)==4){        ll s=compute(n[tag-1],radix);        tag=2-tag;        ll low=2,high=s+1,mid;        for(int j=0;n[tag][j]!='\0';j++)            low=max(low,cton(n[tag][j])+1);        while(low<=high){            mid=low+(high-low)/2;            int t=cmp(n[tag],mid,s);            if(t==0) break;            else if(t==-1) low=mid+1;            else high=mid-1;        }        if(low<=high) printf("%lld\n",mid);        else printf("Impossible\n");    }    return 0;}


原创粉丝点击