题目信息
1010 Radix (25)(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 10
Sample Output 1:
2
Sample Input 2:
1 ab 1 2
Sample Output 2:
Impossible
代码
#include<iostream>
#include<cctype>
using namespace std;
long long to_decimal(string s,long long radix){
long long sum=0;
for(int i=0;i<s.length();i++){
sum=sum*radix;
if(isdigit(s[i])) sum+=s[i]-'0';
if(isalpha(s[i])) sum+=s[i]-'a'+10;
}
return sum;
}
long long find_left(string s){
int max=0;
for(int i=0;i<s.length();i++){
if(isdigit(s[i])&&s[i]-'0'>max) max=s[i]-'0';
if(isalpha(s[i])&&s[i]-'a'+10>max) max=s[i]-'a'+10;
}
return max;
}
long long binarySearch(string s,long long left,long long right,long long dec){
long long mid,s_dec;
while(left<=right){
mid=(left+right)/2;
s_dec=to_decimal(s,mid);
if(s_dec<0||s_dec>dec) right=mid-1;//若转换后的十进制数溢出(一定是radix选大了)或较大
else if(s_dec<dec) left=mid+1;//选小了
if(s_dec==dec) return mid;//返回此时的mid即为最终所找的radix
}
return -1;
}
int main(){
string n1,n2;
long long tag,radix,dec1,dec2,flag;
cin >> n1 >> n2 >> tag >> radix;
if(tag==1){
dec1=to_decimal(n1,radix);
long long left=find_left(n2);
flag=binarySearch(n2,left+1,dec1+1,dec1);
}else{
dec2=to_decimal(n2,radix);
long long left=find_left(n1);
flag=binarySearch(n1,left+1,dec2+1,dec2);
}
if(flag==-1) cout<<"Impossible";
else cout<<flag;
return 0;
}