1010. Radix (25)

来源:互联网 发布:双针探底公式源码 编辑:程序博客网 时间:2024/04/29 03:19

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
如果不加二分查找,则有一个case超时。一定一定注意在把字符串按基数转化为数值的时候会有溢出的,而且不止一个case检查溢出。所以在转换的时候判断溢出,如果溢出就返回这个类型的最大值。
基数的可能范围的上下界如何确定是这道题的关键所在。
#include <iostream>#include <vector>#include <string>const long long int LLMAX=0x7fffffffffffffff;using namespace std;int char2int(char c){if(c >='0' && c<='9')return c-'0';if(c >= 'a' && c<='z')return c-'a'+10;}long long str2int(const string & str,long long radix){long long num=0;for(long long i=0;i<str.size();i++){num=num*radix+char2int(str[i]);if(num < 0)//这里会溢出,当溢出的时候一定大于目标值,所以设置为long long 的最大值return LLMAX;}return num;}long long find_lower(const string & str){long long max=-1;for(long long i=0;i<str.size();i++){long long t = char2int(str[i]);if(t > max){max=t;}}return max;}int main(){string str1,str2;long long tag,radix;cin>>str1>>str2>>tag>>radix;if(tag == 2){string temp=str1;str1=str2;str2=temp;}long long target=str2int(str1,radix);long long lower=find_lower(str2)+1;long long upper=target>lower?target:lower;bool ok=false;long long l = lower,r=upper;long long res,mid; while(l < r){mid=(l+r)/2;res=str2int(str2,mid);if(res < target)l=mid+1;elser=mid;}res=str2int(str2,r);if(res == target)cout<<r<<endl;elsecout<<"Impossible\n";return 0;}


0 0
原创粉丝点击