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 N 1 N_1 N1 and N 2 N_2 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.
Sample Input 1:
6 110 1 10
Sample Output 1:
2
Sample Input 2:
1 ab 1 2
Sample Output 2:
Impossible
思路
如果我们用暴力去求解的话,可能会超时,因此我们采用二分的方法,为什么能用二分呢?因为本道题具有二段性,即我们在直线上假设 x x x 是我们的答案,我们发现,如果我们枚举的 t < x t<x t<x 的话,此时就得让 t t t 变大,我们怎么让 t t t 变大呢,当然是让进制数增加,因此就满足了单调性。如果进制数过大导致我们的数很大,此时缩小进制数,因此满足二段性。
那么本道题的代码就很好写了。
- 细节1:建议开 unsigned long long。
- 细节2:因为由 tag 取值为 1 或 2 的情况,此时我们为了保证代码的简洁,此时就 swap 一下字符串 a 和 b 。
- 细节3:判断无解的情况就是将 r 带入 calc 函数判断是否等于 n1。
代码
//二分
#include<iostream>
#include<algorithm>
#include<cstring>
#define int unsigned long long
using namespace std;
string a,b;
int tag,r;
int n1,n2;
int calc(int x){
n2=0;
for(int i=0;i<b.size();i++){
n2=n2*x+(b[i]>='a'&&b[i]<='z'?(int)b[i]-'a'+10:(int)b[i]-'0');
}
// cout<<"("<<n2<<")"<<x<<" "<<n1<<" "<<(n2>n1)<<endl;
return n2;
}
signed main(){
cin>>a>>b>>tag>>r;
if(tag==2)swap(a,b);
for(int i=0;i<a.size();i++){
n1=n1*r+(a[i]>='a'&&a[i]<='z'?(int)a[i]-'a'+10:(int)a[i]-'0');
}
// cout<<n1<<endl;
int mx=0;
for(int i=0;i<b.size();i++){
mx=max(mx,(int)b[i]>='a'&&b[i]<='z'?(int)b[i]-'a'+10:(int)b[i]-'0');
}
// cout<<mx<<endl;
int l=mx,r=1e18;
while(l+1!=r){
int mid=l+r>>1;
if((calc(mid)>=n1))r=mid;
else l=mid;
}
// cout<<r<<endl;
// cout<<calc(r)<<endl;
if(calc(r)!=n1){
puts("Impossible");
}else{
cout<<r<<endl;
}
return 0;
}