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.

Sample Input 1:

6 110 1 10

Sample Output 1:

2

Sample Input 2:

1 ab 1 2

Sample Output 2:

Impossible

题意是: 

N1 N2 tag radix ,N1,N2分别不超过十位,并且又数字和小写字母组成

当tag = 1的时候N1是radix的基数,当tag = 2的时候N2是radix的基数

找未知数的最小基数看未知数是否与已知数相等。

我把需要找基数的那个数称为 未知数。

坑点:基数的范围,基数的范围应该是无穷的,但是我们可以根据题意把基数局限在一个有效的范围,基数的下限是:未知数的最大字符 + 1,上限是:已知数。 因为我们要找基数来达到未知数 = 已知数的目的,那么未知数的基数是不可能大于已知数的。

找到上限和下限就可以二分了。

N1, N2都应该用string  转换后的数 要用 long long

参考了​​参考柳婼大神的代码​​ 发现大神好喜欢用 三目运算符

学习到了很多新的函数:比如:*max_element(n.begin(), n.end());  

convert函数是把字符串根据一个进制转换成相应的数字

find_radix函数是二分找基数

//radix 基数
//如果 tag == 1 基数是N1的基数
//如果 tag == 2 基数是N2的基数
// 题中给的 已经基数 转换 后是不会溢出的
// radix_下限:遍历位置数的每一位,得到单个位的最大值 + 1
// radix_上限:因为如果N1 = N2 那么未知数的基数不可能 大于 已知数
#include <bits/stdc++.h>
#define ll long long
using namespace std;
string N1, N2;
int tag;
ll radix=0,result_radix;
ll convert(string n,ll radix){
ll sum = 0;
int index = 0, temp = 0;
for(auto it = n.rbegin();it != n.rend(); it++) {
temp = isdigit(*it) ? *it - '0' : *it - 'a' + 10;
sum += temp * pow(radix, index++);
}
return sum;
}
ll find_radix(string n,ll num){
char it = *max_element(n.begin(), n.end());
ll low = (isdigit(it)?it - '0' : it - 'a' + 10) + 1;
ll high = max(num ,low);
while (low <= high) {
ll mid = (low+high) >> 1;
ll t = convert(n,mid);
if(t < 0 || t > num) high = mid - 1; //t<0 是因为溢出
else if( t == num ) return mid;
else low = mid + 1;
}
return -1;
}
int main(){

cin >> N1 >> N2 >> tag >> radix;
result_radix = tag == 1 ? find_radix(N2, convert(N1,radix)) : find_radix(N1, convert(N2,radix));
if (result_radix != -1){
cout << result_radix << endl;
}else {
cout << "Impossible" <<endl;
}
return 0;
}