这个题目应用long long 才不超出范围。首先将已经进制的数转为10进制数结果为sum,如果超出long long范围 则直接输出impossible,否则进行二分查找基数,l为最小的进制数(为字符串中最大的字符对应的10进制数+1),r为最大的进制数(为sum+1),进行二分查找。
AC代码:
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<stack>
#define eps 0xfffffffffffff
#include<queue>
#include<map>
using namespace std;
int main()
{
string a,b;
int c;
long long d;
cin>>a>>b;
scanf("%d %lld",&c,&d);
if(c==2)
{
swap(a,b);
}
long long sum=0;
long long tmp;
int len=a.size();
for(int i=0;i<len;i++)
{
if(a[i]>='0'&&a[i]<='9')
{
tmp=a[i]-'0';
}
else
{
tmp=a[i]-'a'+10;
}
sum=sum*d+tmp;
if(sum<0)
{
sum=-1;
break;
}
}
cout<<sum<<endl;
char maxx='1';
for(int i=0;i<b.size();i++)
{
if(b[i]>maxx)
maxx=b[i];
}
long long minjz;
if(maxx>='0'&&maxx<='9')
{
minjz=maxx-'0'+1;
}
else
{
minjz=maxx-'a'+11;
}
//cout<<minjz<<endl;
long long l=minjz;
long long r=sum+1;
//cout<<l<<" "<<r<<endl;
while(l<=r)
{
long long mid=(r+l)/2;
long long sum1=0;
long long tmp;
for(int i=0;i<b.size();i++)
{
if(b[i]>='0'&&b[i]<='9')
{
tmp=b[i]-'0';
}
else
{
tmp=b[i]-'a'+10;
}
sum1=sum1*mid+tmp;
if(sum1<0)
{
sum1=-1;
break;
}
}
if(sum1==-1||sum1>sum)
{
r=mid-1;
}
else if(sum1<sum)
{
l=mid+1;
}
else
{
cout<<mid;
return 0;
}
}
printf("Impossible");
}