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
题意:进制转换,给出2个数,后面跟着tag,和radix的值,tag表示第几个数的进制是radix,要找出另外一个数的进制能和这个radix进制的数相等。题目没给出进制的范围,所以需要用到long long类型。
解题思路:这题单纯模拟有4个测试点过不了,所以扣了4分,然后通过看别人博客的解题思路,才知道要用二分法查找,当时没多想就顺序搜索,看了他们的思路,将自己的代码改了一遍。就增加了一个二分查找函数find_radix(string s,int num),将当前的进制和另外一个转换的数比较,如果当前进制比另外一个大,就说明这个进制太大了,但在转换的时候可能会溢出,所以小于0也说明太大了,这时将high=mid-1,如果等于当前的就直接返回这个mid,如果是其他情况,就说明比较小,将low=mid+1,具体见代码
#include<bits/stdc++.h>
using namespace std;
string n1,n2;
long long radix;
long long change(string s,long long r)
{
int n=s.length(),k=0,sum=0;
for(int i=n-1;i>=0;i--)
{ if(isdigit(s[i])) {
sum+=(s[i]-'0')*pow(r,k);
}else if(isalpha(s[i]))
sum+=(s[i]-'W')*pow(r,k);
k++;
}
return sum;
}
long long find_radix(string n,long long num)
{
char m=*(max_element(n.begin(),n.end()));
long long low=(isdigit(m)?m-'0':m-'a'+10)+1;
long long high=max(low,num);
while(low<=high)
{
long long mid=(high+low)/2;
long long sum=change(n,mid);
if(sum<0||sum>num) high=mid-1;
else if(sum==num) return mid;
else low=mid+1;
}
return -1;
}
int main(void)
{
int tag;
cin>>n1>>n2;
cin>>tag>>radix;
string n,an;
long long ans;
if(tag==1) n=n1,an=n2;
else if(tag==2) n=n2,an=n1;
ans=find_radix(an,change(n,radix));
if(ans==-1)printf("Impossible");
else printf("%lld",ans);
return 0;
}