Given a pair of positive integers, for example, 6 6 6 and 110 110 110, can this equation 6 = 110 6 = 110 6=110 be true? The answer is yes, if 6 6 6 is a decimal number and 110 110 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 4 4 positive integers:
N1 N2 tag radix
Here N 1 N_1 N1 and N 2 N_2 N2 each has no more than 10 10 10 digits. A digit is less than its radix and is chosen from the set { 0 − 9 , a − z 0-9, a-z 0−9,a−z } where 0 − 9 0-9 0−9 represent the decimal numbers 0 − 9 0-9 0−9, and a − z a-z a−z represent the decimal numbers 10 − 35 10-35 10−35. The last number radix is the radix of N 1 N_1 N1 if tag is 1 1 1, or of N 2 N_2 N2 if tag is 2 2 2.
Output Specification:
For each test case, print in one line the radix of the other number so that the equation N 1 = N 2 N_1 = N_2 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
题解:
前
10
10
10 题里最难的一题了,考点主要有:任意进制到十进制数的转换、二分法的应用、大数溢出,其中大数溢出比较坑。。。
本题若不使用二分法,而采用从radix = 2开始遍历的方式,则无法通过测试点7;但若使用二分法而没有判断大数溢出的情况,则会有很多测试点不通过。
注意事项:
- 将任意进制的数转换为十进制数:
int sum = 0; // 此处需要注意判断 sum 的范围, 必要时应使用 long long
for(int i=0;num[i]!='\0';i++
sum = sum*radix + num[i] - '0';
- 关于大数溢出的判断方法:
long long num;
...... // 此处保证正常情况下 num >= 0
if(num < 0)
// 溢出
- 二分查找
while(low<=high){
mid = low + (high-low)/2; // 避免 (low+high) 发生溢出
if(...)
low = mid + 1;
else
high = mid - 1;
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
long long trans2dec(char* num, long long radix)
{
long long sum = 0;
for(int i=0;num[i]!='\0';i++){
if(num[i]>='0' && num[i]<='9')
sum = sum*radix + num[i] - '0';
else
sum = sum*radix + num[i] - 'a' + 10;
}
return sum;
}
int main()
{
char num[2][12] = {'\0'};
int tag;
long long radix, N1,N2;
cin>>num[0]>>num[1]>>tag>>radix;
N1 = trans2dec(num[tag-1],radix);
radix = 1;
for(int i=0;num[2-tag][i]!='\0';i++){
if(num[2-tag][i]>='0' && num[2-tag][i]<='9'){
if(radix < num[2-tag][i] - '0')
radix = num[2-tag][i] - '0';
}
else
if(radix < num[2-tag][i] - 'a' + 10)
radix = num[2-tag][i] - 'a' + 10;
}
long long low = radix + 1;
long long high = N1 + 1;
while(low <= high){
radix = low + (high - low)/2;
N2 = trans2dec(num[2-tag], radix);
if(N1 == N2){
cout<<radix;
return 0;
}
else if(N2 < 0 || N2 > N1){ // 当 N2 溢出时,其值为负!
high = radix - 1;
}
else{
low = radix + 1;
}
}
cout<<"Impossible";
}