标签:
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
思路:时刻记住要判断是否会出现溢出的情况,另外字符转换ASCII码的时候注意简便的转换方式。
1 #include <iostream> 2 #include <cstring> 3 #include <algorithm> 4 using namespace std; 5 const long long inf=(1ll<<63)-1; 6 long long Change(char A [],int r) 7 { 8 long long sum=0; 9 for(int i=0;A[i]!=‘\0‘;i++) 10 { 11 if(A[i]>=‘0‘&&A[i]<=‘9‘) 12 { 13 sum*=r; 14 sum+=(A[i]-‘0‘); 15 if(sum<0||sum>inf) //需要判断溢出检验 16 return -1; 17 } 18 else if(A[i]>=‘a‘&&A[i]<=‘z‘) 19 { 20 sum*=r; 21 sum+=(A[i]-‘a‘+10); //好想法 22 if(sum<0||sum>inf) 23 return -1; 24 } 25 } 26 return sum; 27 } 28 int Find(char A[]) 29 { 30 int ans=-1; 31 for(int i=0;A[i]!=‘\0‘;i++) 32 { 33 int tem; 34 if(A[i]>=‘0‘&&A[i]<=‘9‘) 35 { 36 tem=A[i]-‘0‘; 37 } 38 else 39 { 40 tem=A[i]-‘a‘+10; 41 } 42 if(tem>ans) 43 { 44 ans=tem; 45 } 46 } 47 return ans+1; 48 49 } 50 51 52 int main(int argc, char *argv[]) 53 { 54 //需要利用N1存储已经知道的数字,N2存储不知道的数字 55 char N1[10],N2[10]; 56 long long tag,radix; 57 scanf("%s%s%lld%lld",&N1,&N2,&tag,&radix); 58 if(tag==2) 59 { 60 char temp[10]; 61 strcpy(temp,N1); 62 strcpy(N1,N2); 63 strcpy(N2,temp); 64 } 65 long long res = Change(N1,radix); 66 long long left=Find(N2); 67 long long right=max(left,res)+1;//好东西 //需要重新找上下界 68 bool flag=false; 69 long long rad; 70 while(left<=right&&strcmp(N1,N2)) 71 { 72 long long mid=(left+right)/2; 73 long long ans=Change(N2,mid); 74 if(ans==res) 75 { 76 flag=true; 77 rad=mid; 78 break; 79 } 80 if(ans>res||ans==-1) 81 { 82 right=mid-1; 83 } 84 else 85 { 86 left=mid+1; 87 } 88 } 89 if(!strcmp(N1,N2)) 90 printf("%d\n",radix); 91 else if(flag) 92 printf("%lld\n",rad); 93 else 94 printf("Impossible\n"); 95 return 0; 96 }
标签:
原文地址:http://www.cnblogs.com/GoFly/p/4295118.html