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
/**
题意:
n1 n2 是否能在某种进制下相等,求出该进制
tag = 1 radix表示为n1的进制
= 2表示为n2的进制
题解:
最小的进制肯定是n1中最大的数位+1,
最大的进制却不是26,而是n1+1,表示n2用一位就能表示n1
所以不能用for循环枚举,而是用二分查找
注意数据范围要用long long
注意在x进制下n2可能溢出,这时应该将查找区域固定到左半边
*/
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
typedef long long ll;
const int maxn = 2000+10;
const int INF = 0x3f3f3f3f;
ll change(char c){
if(c >= '0' && c <= '9')
return c-'0';
else return c-'a'+10;
}
ll getval(string s,int x){///在x进制下 s转化为十进制的数值为
ll res = 0;
for(int i = 0;i<s.length();++i){
res *= x;
res += change(s[i]);
if(res < 0) return -1;///这里注意res可能溢出
}
return res;
}
int main(){
string n1,n2,t;
int tag,radix;
cin>> n1>>n2>>tag>>radix;
if(tag == 2 ){ ///让n1总是表示参照的
t = n1;
n1 = n2;
n2 = t;
}
ll n1val = getval(n1,radix);
ll low = 0, high, mid;
for(int i = 0;i<n2.length();++i){
if(change(n2[i]) > low) low = change(n2[i]);
}
low++;
high = n1val+1;
bool f = 0;
while(low <= high){
mid = (low+high)/2;
ll midval = getval(n2,mid);
if(midval < 0 || midval > n1val)
high = mid -1;
else if(midval < n1val)
low = mid +1;
else if(midval = n1val) {
f = 1;
break;
}
}
if(f) cout << mid;
else cout<<"Impossible";
return 0;
}