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 10Sample Output 1:
2Sample Input 2:
1 ab 1 2Sample Output 2:
Impossible
二分法,另外右界进制的取值还是不是很懂
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
typedef long ll;
ll trans_dec(string n, int radix);
int main()
{
int tag, radix;
ll target, res;
ll leftradix, rightradix ,mid;
string n1, n2;
cin >> n1 >> n2 >> tag >> radix;
if(tag == 2)
swap(n1, n2);
target = trans_dec(n1, radix);//目标数的10进制表示
leftradix = 0;
for(string::size_type i=0; i<n2.size(); i++)//最小进制至少大于该数中最大的那个数+1
{
int temp;
if(isalpha(n2[i]))
temp = n2[i]-'a'+10;
else
temp = n2[i]-'0';
if(temp > leftradix)
leftradix = temp+1;
}
rightradix = target+1;//最大进制不是很理解
while(leftradix <= rightradix)//二分法
{
mid = (rightradix+leftradix)/2;
res = trans_dec(n2, mid);
if(res > target || res == -1)//结果大于目标和超出范围都表示右界较大
rightradix = mid-1;
else if(res < target)//小于则左界较小
leftradix = mid+1;
else if(res == target)
break;
}
if(leftradix > rightradix)
cout << "Impossible" << endl;
else
cout << mid;
return 0;
}
ll trans_dec(string n, int radix)
{
ll num = 0;
int temp;
for(string::size_type i=0; i<n.size(); i++)
{
if(isalpha(n[i]))
temp = n[i]-'a'+10;
else
temp = n[i]-'0';
num *= radix;
num += temp;
if(num < 0)//因为进制很大时可能会超出范围,当超出时返回-1
return -1;
}
return num;
}