用顺序查找的方式搜第七个测试点过不去,二分查找是一个办法,注意这里low和high的取值,high的取值我是这样想的:当n2长度为1时进制数最多为low,否则长度大于1时进制数最多为res1(若为(res1+1)就必定会有res2>res1了,肯定不满足)
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main(){
string n1,n2; int tag,rad;
cin>>n1>>n2>>tag>>rad;
if(tag!=1) swap(n1,n2);
ll res1=0;
for(int i=0;i<n1.size();i++){
int cur=(n1[i]<='9'?n1[i]-'0':n1[i]-'a'+10);
res1*=rad;
res1+=cur;
}
char it = *max_element(n2.begin(),n2.end());
ll low = (it<='9'?it-'0':it-'a'+10)+1;
ll high = max(res1,low);
while(low<=high){
ll mid = low+(high-low)/2;
int cur;ll res2=0;
for(int j=0;j<n2.size();j++){
cur=(n2[j]<='9'?n2[j]-'0':n2[j]-'a'+10);
res2*=mid;
res2+=cur;
}
if(res2>res1||res2<0){
high=mid-1;
}else if(res2<res1){
low=mid+1;
}else{
printf("%lld",mid);
return 0;
}
}
printf("Impossible");
return 0;
}