1010. Radix (25)
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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 解析:这题主要需要注意一些细节,比如如何防止radix过大的情况,在下面的解法中使用的是long long来存储化成十进制的值 Code:
#include<cstdio> #include<cstring> #include<iostream> using namespace std; typedef long long ll; const ll inf=0x7fffffffffffffff; char a[15],b[15],c[15]; ll da,db; ll value(char *a,ll r){ ll ans=0; for(int i=0;a[i];++i){ if(a[i]<=‘9‘){ ans=ans*r+a[i]-48; }else{ ans=ans*r+a[i]-87; } if(ans<0 || ans>da) return inf; } return ans; } int cnta,cntb,n; int main(){ int i,type; ll l,r,m; scanf("%s%s%d%lld",a,b,&type,&r); if(type==2){ strcpy(c,a); strcpy(a,b); strcpy(b,c); } da=inf; da=value(a,r); r=0; for(i=0;b[i];++i) if(b[i]>r) r=b[i]; if(r<=‘9‘) r-=47; else r-=86; l=r;r=da; while(l<r){ m=(l+r)>>1; db=value(b,m); if(db<da) l=m+1; else if(db>da) r=m-1; else r=m; } if(value(b,l)==da) printf("%lld\n",l); else if(value(b,r)==da) printf("%lld\n",r); else printf("Impossible\n"); return 0; }