原题
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 N1and 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.
题意
就是给两个数,告诉你其中一个数的进制,问另外一个数能不能在某个进制的情况下导致这两个数相等。
单词难点:radix (进制,基数)
思路
先将告诉了进制的数转换为十进制。另外一个数在各种进制下转换为十进制判断其是否相等。
难点
①暴力枚举超时,由于会产生a-z且位数最大可以达到10位,进制可能性庞大。会导致严重超时。解决方案是由于进制转换有明显的数字大小单调变化,所以可以采用二分解决。
②数字过大,需要采用long long来储存
代码
#include<iostream>
#include<cmath>
#include<cctype>
#include<algorithm>
using namespace std;
//radix 基数,进制
long long Convert(string n,int radix){
long long result=0;
for(int i=n.size()-1;i>=0;i--){
int temp=(isdigit(n[i])?n[i]-'0':(n[i]-'a'+10));
result+=temp*pow(radix,n.size()-i-1);
}
return result;
}
int Findresult(string n1,string n2,long long radix){
char it =*max_element(n2.begin(),n2.end());
long long low=(isdigit(it)?it-'0':it-'a'+10)+1;
long long resnum = Convert(n1,radix);
long long high=max(low,resnum);
while(low<=high){
long long mid=(low+high)/2;
long long result =Convert(n2,mid);
if(result==resnum){
return mid;
}else if(result>resnum||result<0){
high=mid-1;
}else{
low=mid+1;
}
}
return -1;
}
int main(){
string n1,n2;
int tag;
long long radix;
long long resultnum;
cin>>n1>>n2>>tag>>radix;
resultnum=tag==1?Findresult(n1,n2,radix):Findresult(n2,n1,radix);
if(resultnum!=-1){
cout<<resultnum;
}else{
cout<<"Impossible";
}
}