思路:题目是判断第tag数的radix进制等与另外一个数的多少进制?如果存在,输出最小的;如果不存在,输出Impossible。注意:由于测试数据存在一个极大的进制,需要使用二分法去判断。如需要通过如下测试数据: 1234567891 11 1 10 输出:1234567890
目的:二分法 进制
题目描述:
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 10Sample Output 1:
2Sample Input 2:
1 ab 1 2Sample Output 2:
Impossible
参考代码:
#include <iostream> #include <utility> using namespace std; #include <string.h> #include <math.h> //把数组转换为n进制数 long long atoN(char *a,long long n) { long long sum=0; while(*a) sum=sum*n+(*a>='0'&&*a<='9'?*a++-'0':*a++-'a'+10); return sum; } //获得字符串s,最小的合法进制 int lessValidRadix(char *a) { int radix=2; while(*a) { int t=*a++-'0'; if(t>=10) t=t+'0'-'a'+10; if (radix<t+1) radix=t+1; } return radix; } int main() { char s1[11]; char s2[11]; int tag,radix; while(cin>>s1>>s2>>tag>>radix) { if (tag==2) swap(s1,s2); long long n1=atoN(s1,radix); long long left=lessValidRadix(s2); long long right; if(strlen(s2)==1) right=36; else right=(long long)pow((double)n1,1.0/(strlen(s2)-1)); long long mid; for(mid=(left+right)/2;left+1<right;mid=(left+right)/2) { long long n2=atoN(s2,mid); if(n1>n2) left=mid+1; else right=mid; } if (n1==atoN(s2,left)) cout<<left<<endl; else if(n1==atoN(s2,right)) cout<<right<<endl; else cout<<"Impossible"<<endl; } return 0; }