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 N?1?? and N?2??, 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
思路:将给定的数转换成十进制数,然后对另一个数字用循环逐个找到对应进制的十进制数的大小 本来用stoi函数的,写的很方便,但是通过牛客给的测试数据发现,stoi的进制范围是有要求的,2-36进制的准换难点:(1)进制范围的确定,下界 l 等于待测的数字的各个位上的最大的数+1,上届是给定数字的十进制形式+1 (2) 要用long long 以及对于代码中溢出的处理 ,,,,long long 溢出后小于零疑问:题中要求如果答案不唯一,那么输出最小的,但是感觉二分来写会满足不了题意,但是最后ac了
代码如下:
1 #include <cstdio> 2 #include <string> 3 #include <iostream> 4 #include <algorithm> 5 #define LL long long 6 using namespace std; 7 8 LL ch_num(string s,int r){ 9 LL res=0; 10 int len=s.length(); 11 for(int i=0;i<len;i++){ 12 if(s[i]>=‘0‘&&s[i]<=‘9‘) 13 res=res*r+(s[i]-‘0‘); 14 else 15 res=res*r+(s[i]-‘W‘); 16 } 17 if(res<0) 18 return -1;//溢出处理 19 return res; 20 } 21 LL maxcnt(string s){ 22 LL maxn=0,t; 23 int len=s.length(); 24 for(int i=0;i<len;i++){ 25 if(s[i]>=‘0‘&&s[i]<=‘9‘){ 26 t=s[i]-‘0‘; 27 maxn=max(maxn,t); 28 } 29 else{ 30 t=s[i]-‘W‘; 31 maxn=max(maxn,t); 32 } 33 } 34 return maxn+1; 35 } 36 37 int main(void) 38 { 39 int tag,rad; 40 string fin,sen; 41 cin>>fin>>sen>>tag>>rad; 42 43 LL num,l; 44 string str; 45 if(tag==1){ 46 num=ch_num(fin,rad); 47 l=maxcnt(sen); 48 str=sen; 49 } 50 else{ 51 num=ch_num(sen,rad); 52 l=maxcnt(fin); 53 str=fin; 54 } 55 56 LL mid,tem; 57 LL r=num+1; 58 while(l<=r){ 59 mid=(l+r)>>1; 60 tem=ch_num(str,mid); 61 if(tem==num){ 62 printf("%lld\n",mid); 63 return 0; 64 } 65 if(tem>num || tem==-1) 66 r=mid-1; 67 else 68 l=mid+1; 69 } 70 printf("Impossible\n"); 71 72 return 0; 73 }
原文地址:https://www.cnblogs.com/gn1314/p/12141626.html