1010. Radix (25)

来源:互联网 发布:pstn网络 编辑:程序博客网 时间:2024/05/14 13: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
注意:
1、首先要理解好题目的意思,给出N1 N2 tag radix这四个参数,radix表示的是tag所指定的的参数的进制式(tag=1时指定的是N1,tag=2时指定的是N2),而要解决的问题则是求得未给定进制式的参数的可能的进制式,使得N1和N2两个参数在各自的进制式下的数值相等。因此这里需要使用到遍历,而考虑到时间和效率,这里最好使用二分法来搜索。
2、注意PAT的编译器关于string操作的函数能通过编译的头文件是cstring,所以这里要#include<cstring>而不是#include<string>。
3、要考虑到在使用某一个进制进行转换时,如果该进制很大,有可能会出现long long类型仍然会溢出的情况,这时候计算得到的数值为一负数,因此在转换函数时要考虑这种情况。if(num<0) return -1; 并且在主函数中对这种情况进行处理。
4、无论是改变搜索界限还是初始化界限,都要十分注意+1和-1的情况,在while循环的时候要小心停止的条件,在上下界相等的时候也需要进行一次计算,不然会漏掉可能的正确结果。
5、貌似题目中要求的输出最小的可能值并没有在这里得到体现啊!

代码:
#include <iostream>#include <cstring>using namespace std;int getnum(char p){if(p<='9' & p>='0')return p-'0' ;else return p-'a'+10;}long long str2num(char *p, long long rad){long long num=0;for(int i=0;i<strlen(p);i++){num=num*rad+getnum(p[i]);if (num<0) return -1;}return num;}int main(){char a[15],b[15];int tag;long long radix;cin>>a>>b>>tag>>radix;if(tag==2){char temp[15];strcpy(temp,a);strcpy(a,b);strcpy(b,temp);}long long n=0;n=str2num(a,radix);long long threshold[2]={2,n+1};for(int i=0;i<strlen(b);i++)threshold[0]=threshold[0]<getnum(b[i])?getnum(b[i])+1:threshold[0];long long targetradix,t;while(threshold[1]>=threshold[0]){targetradix=(threshold[0]+threshold[1])/2;t=str2num(b,targetradix);if(n==t){cout<<targetradix<<endl;return 0;}else if (-1==t||n<t)threshold[1]=targetradix-1;else threshold[0]=targetradix+1;}cout<< "Impossible"<<endl;return 0;}

0 0