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.
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.
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.
6 110 1 10
2
1 ab 1 2
Impossible
一,注意点
1,第一个误区是本题中给出了数值的取值范围是0到35我就以为进制的范围就是1到36了,不是的!进制的下界是N2中最小的那一位加1,上界是N1的十进制数值。
2,第二个误区是以为N1的十进制数值不会溢出,实际上是会的,处理方法是若是溢出了返回-1,此时进制的上界变成了0,在二分中很显然就是Impossible.
二,我的代码
#include
#include
#include
using namespace std;
typedef long long LL;
LL INF = (1LL << 63) - 1;
int switch_str_to_num(char a) {
if (a >= '0'&&a <= '9') {
return a - '0';
}
else {
return a - 'a' + 10;
}
}
LL switch_to_radix(char num[], LL radix, LL t) {
int len = strlen(num);
LL ans = 0;
for (int i = 0; i < len; i++) {
ans = radix*ans + switch_str_to_num(num[i]);
if (ans < 0||ans > t) {
return -1;
}
}
return ans;
}
int find_min_radix(char num[]) {
int min_radix = 0;
int len = strlen(num);
for (int i = 0; i < len; i++) {
if (min_radix < switch_str_to_num(num[i])) {
min_radix = switch_str_to_num(num[i]);
}
}
return min_radix + 1;
}
LL binary_search(char num[], LL left, LL right, LL x) {
LL mid;
if (switch_to_radix(num, left, INF) == x) {
return left;
}
else {
while (left <= right) {
mid = (left + right) / 2;
if (switch_to_radix(num, mid, INF) == x) {
return mid;
}
else if (switch_to_radix(num, mid, INF) > x || switch_to_radix(num, mid, INF) == -1) {
right = mid - 1;
}
else {
left = mid + 1;
}
}
}
return -1;
}
int main() {
char N1[14], N2[14], temp[14];
int tag = 0, radix_1 = 0, radix_2 = 0;
LL sum_1 = 0;
LL lowest_radix = 0, highest_radix = 0;
// int lowest_radix_1 = 0, lowest_radix_2 = 0, lowest_radix = 0;
LL ans = 0;
scanf("%s", N1);
scanf("%s", N2);
scanf("%d", &tag);
scanf("%d", &radix_1);
if (tag == 2) {
strcpy(temp, N1);
strcpy(N1, N2);
strcpy(N2, temp);
}
// lowest_radix_1 = find_min_radix(N1);
lowest_radix = find_min_radix(N2);
// lowest_radix = max(lowest_radix_1, lowest_radix_2);
sum_1 = switch_to_radix(N1, radix_1, INF);
highest_radix = sum_1 + 1;
// printf("%lld", ans_1);
ans = binary_search(N2, lowest_radix, highest_radix, sum_1);
if (ans != -1) {
printf("%d", ans);
}
else {
printf("Impossible");
}
return 0;
}