题目
1010 Radix (25分)
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,其中tag、radix用于表示已知进制的数,求出能够使得两个数相等的另一个数字的进制,如果不存在则输出Impossible
思路
先将已知进制的数字转化为十进制数保存,然后通过遍历进制数来找到有无使得转化后的目标数和已知数相等的进制数,这是最初的想法。
但是做的时候:
- 以为进制只能是2-36
- 解决上面的想法后,由于遍历,导致超时,以及进制不同时可能会导致运算时溢出
- 所以还需要使用二分查找,溢出时num<0需要加以判断
代码
#include<bits/stdc++.h>
using namespace std;
map<char, int> char2int;
long long getNum(string s, long long r){
// 转化为十进制
long long sum = 0, p = 0;
for(long long i = s.size() - 1; i>=0; i--){
sum += pow(r, p++) * char2int[s[i]];
}
return sum;
}
long long find_radix(string s, long long num){
long long low = char2int[*max_element(s.begin(), s.end())] + 1;
long long high = max(num, low);
while(low <= high){
long long mid = (low + high) / 2;
long long t = getNum(s, mid);
if(t > num || t < 0) high = mid - 1;
else if(t == num) return mid;
else low = mid + 1;
}
return -1;
}
int main(){
for(int i=0; i<10; i++)
char2int[i + '0'] = i;
for(int i=0; i<26; i++)
char2int['a' + i] = i + 10;
string N1, N2, tmpN;
long long num, tag, radix;;
cin>>N1>>N2>>tag>>radix;
if(tag == 1){
num = getNum(N1, radix);
tmpN = N2;
}else{
num = getNum(N2, radix);
tmpN = N1;
}
long long r = find_radix(tmpN, num);
if(r != -1)
printf("%lld", r);
else
printf("Impossible");
return 0;
}