坑贼多
- 结果 Radix 可能非常大, 我一开始以为最大就到35, 其实不然, 所以昨天只有 18分
- 时间复杂度, 当radix非常大时, 顺序遍历就会 超时了, 所以采用二分法查找
- 每次 试探 一个 radix 得出的值可能溢出 long long int 范围变成负数, 此时要判断, 舍去更大的radix
题目
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 N1N_1N1 and N2N_2N2, 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
代码
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
long long int radix2ten(char *digit, long long int radix){
long long int res = 0L;
int i = 0;
int c;
int d;
int len = 0;
for(; digit[len] != '\0'; len++);
i = 0;
while(digit[i] != '\0'){
c = (int)digit[i];
d = (int)(c > 95?(c-'a'+10):(c-'0'));
res += d * pow((double)radix, (double)(len-i-1));
i++;
}
return res;
}
void half(long long int minRadix, long long int maxRadix, long long int tl, char digit[]){
if(minRadix>maxRadix){
printf("Impossible");
return;
}
long long int middle = (minRadix+maxRadix)/2;
long long int l = radix2ten(digit, middle);
if(l > tl || l < 0){ // l>tl 或者 l 溢出 long long int
half(minRadix, middle-1, tl, digit);
}else if (l < tl){
half(middle+1, maxRadix, tl, digit);
}else{
printf("%ld", middle);
}
}
int main(void){
char n[15];
char m[15];
int tag;
long long int tRadix;
scanf("%s %s %d %ld", n, m, &tag, &tRadix);
long long int tl = radix2ten(tag==1?n:m, tRadix);
long long int i;
long long int l;
char *digit = tag==1?m:n;
int max = 1;
i = 0;
while(digit[i] != '\0'){
if(max < (int)digit[i]){
max = (int)digit[i];
}
i++;
}
max = (int)(max > 95?(max-'a'+10):(max-'0')) ;
i = max+1;
half(i, tl+1, tl, digit);
return 0;
}
总结:
- 溢出的处理
- 复习了二分查找, 进制转换
- 当确认代码没有bug的时候, 就是思路问题 或者 题意理解问题, 一定要读题