#include<iostream>
#include<string>
using namespace std;
long long ToNumber(string n2, int radix){
long long ret=0;
for(int i=0; i<n2.size(); i++){
ret*=radix;
int num = (n2[i]>='0' &&n2[i]<='9') ? (int)(n2[i]-'0') : (int)(n2[i]-'a'+10);
ret += num;
}
return ret;
}
int FindL(string n){
int ret = 0;
for(int i=0; i<n.size(); i++){
int num = (n[i]>='0' &&n[i]<='9') ? (int)(n[i]-'0') : (int)(n[i]-'a'+10);
if(num >ret)
ret = num;
}
return ret;
}
int main(){
string n1, n2;
short c;
int radix;
cin>>n1>>n2>>c>>radix;
long long eq;
if(c == 1){
eq = ToNumber(n1, radix);
}
else{
eq = ToNumber(n2, radix);
n2 = n1;
}
//cout<<eq<<endl;
int le = FindL(n2);
if(n2.size() < 2){
if(ToNumber(n2, le) == eq)
cout<<le+1;
else
cout<<"Impossible";
return 0;
}
long long r = le+1;
long long l = eq;
while(r<=l){
//cout<<n2;
long long i =(r+l)/2;
long long ans = ToNumber(n2, i);
//cout<<ans<<" ";
if(ans == eq){
cout<<i;
return 0;
}
else if(ans > eq || ans < 0){
l = i-1;
}
else
r = i+1;
}
cout<<"Impossible";
return 0;
}
AC代码。
大家思路都差不多,先把确定进制的转十进制存,剩下一个数,进制从最大数字加一到已知十进制数进行二分查找。但这题真的测试案例,被坑到了......尤其是PAT为什么总要自己猜没通过的点的,泪目。
做的时候大概被这些坑了:
1.进制上限不是36!!!(最开始以为这题很简单来着)
2.数据可能很大,别用int!!long long 在二分查找过程也会溢出,所以ans<0强行判断了一波。其实代码还有点问题,关于二分查找的上界确定的方式。如果简单的用比如200作为上界,测试点7会过不去
3.二分法存在一个bug,如果数据只有一位,那么它就会给你一个中间值当进制。测试点0就会过不去。
总归觉得自己更多是骗过去的,也希望有人看到这篇博客可以多多指教。
题目描述:
Given a pair of positive integers, for example, 6 and 110, can this equation 6 = 110 be true? The answer is yes
, if 6 is a decimal number and 110 is a binary number.
Now for any pair of positive integers N1 and N2, your task is to find the radix of one number while that of the other is given.
Input Specification:
Each input file contains one test case. Each case occupies a line which contains 4 positive integers:
N1 N2 tag radix
Here N1
and N2
each has no more than 10 digits. A digit is less than its radix and is chosen from the set { 0-9, a
-z
} where 0-9 represent the decimal numbers 0-9, and a
-z
represent the decimal numbers 10-35. The last number radix
is the radix of N1
if tag
is 1, or of N2
if tag
is 2.
Output Specification:
For each test case, print in one line the radix of the other number so that the equation N1
= N2
is true. If the equation is impossible, print Impossible
. If the solution is not unique, output the smallest possible radix.