1010. Radix (25)

来源:互联网 发布:希尔伯特矩阵的特征值 编辑:程序博客网 时间:2024/06/05 08:09

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

This problem really tortured me for a long time that I totally misunderstood it at the beginning. 

1. I thought the radix must be no more than 36, which took me a long time to understand what it really means.

2. When using binary-search, how to decide the lower bound is still making me confused. There is something wrong with choosing 2 as the lower bound, which I don't know why. ----When I was writing this blog I discussed with my friend this problem, and now I know why. It's insanely obvious... Sigh!

When I'm trying to transfer the number to decimal base, the radix may be too small to be legal. So, it cannot start from 2.

Here is my code which referred toHERE.


#include<iostream>#include<string>#include<cstdlib>#include<algorithm>#include<cmath>using namespace std;long long get_num(char c){return (isdigit(c) ? c - '0' : c - 'a' + 10);}int main(){string s1, s2;int tag, r;cin >> s1 >> s2 >> tag >> r;if (tag == 2)swap(s1, s2);long long n1 = 0, n2 = 0;for (int i = 0; i < s1.size(); ++i)n1 = n1*r + get_num(s1[i]);long long low = 2, high = n1 + 1, mid;for (int i = 0; i<s2.size(); i++)low = max(low, get_num(s2[i]) + 1);while (low <= high){mid = (low + high) / 2;n2 = 0;for (int i = 0; i < s2.size(); ++i)n2 = n2*mid + get_num(s2[i]);if (n2 == n1){cout << mid;return 0;}else if (n2 > n1 || n2 < 0)high = mid - 1;elselow = mid + 1;}cout << "Impossible";return 0;}



原创粉丝点击