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
andN2
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, anda
-z
represent the decimal numbers 10-35. The last numberradix
is the radix ofN1
iftag
is 1, or ofN2
iftag
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, printImpossible
. 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 结尾无空行
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long LL;
// 变为10进制数
LL convert(string str, LL radix)
{
LL len = str.length(), decimal = 0;
for (LL i = 0; i < len; i++)
{
LL n = isdigit(str[i]) ? str[i] - '0' : str[i] - 'a' + 10;
decimal += n * pow(radix, len - i - 1);
}
return decimal;
}
// 二分查找
LL find_radix(string str, LL n1)
{
char n = *max_element(str.begin(), str.end());
LL left = isdigit(n) ? n - '0' + 1 : n - 'a' + 11;
LL right = n1 + 1;
while (left <= right)
{
LL mid = (left + right) / 2;
LL n2 = convert(str, mid);
if (n2 < 0 || n2 > n1)
{
right = mid - 1;
}
else if (n2 == n1)
{
return mid;
}
else
{
left = mid + 1;
}
}
return -1;
}
int main()
{
string s1, s2;
LL tag, radix;
cin >> s1 >> s2 >> tag >> radix;
if (tag == 2)
{
swap(s1, s2);
}
LL n1 = convert(s1, radix);
LL rst = find_radix(s2, n1);
if (rst != -1)
{
printf("%lld", rst);
}
else
{
printf("Impossible");
}
return 0;
}
先把已知进制数转化为十进制,然后未知进制数用不同进制转十进制代入比较,这里使用的是二分查找的方法进行优化。