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
题目大意:给两个数以及其中一个数的进制,判断另一个数有没有可能是这个数不同进制下的形式。
这里采用二分法查找,low为比如eg1中的10最高的数字为1,则它的进制最少为2,high为因为是要与6相等,最进制最大可以取6(即一表示了),这里范围估计得很粗略。
本题的坑还是不少的:
首先算法上,不用二分查找会超时
其实对题目的理解,不要以为只有36个数字或字母,因而最高进制为37,其实他的进制理论上可能无穷大
最后用二分查找带来的附属品,在查找过程中,可能得到的数比 long long int 能表示的范围还要大,此时得到的结果会为负
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
long long int get_num(string s, long long int radix){
long long int ans = 0;
for(int i = 0; i < s.length(); ++ i)
ans = ans * radix + (isdigit(s[i]) ? (s[i] - '0') : (s[i] - 'a' + 10));
return ans;
}
string n1, n2;
long long int tag, radix, Left = 2, Right, temp, result;
int main(){
cin >> n1 >> n2 >> tag >> radix;
if(tag == 2)
swap(n1, n2);
result = get_num(n1, radix);
for(int i = 0; i < n2.length(); ++ i){
temp = (isdigit(n2[i]) ? (n2[i] - '0') : (n2[i] - 'a' + 10)) + 1;
Left = max(Left, temp);
}
Right = max(result, Left);
while(Left <= Right){
long long int mid = Left + ((Right - Left) >> 2);
temp = get_num(n2, mid);
if(temp == result){
printf("%lld", mid);
return 0;
}
else if(temp < 0 || temp > result)
Right = mid - 1;
else
Left = mid + 1;
}
printf("Impossible");
}