您的位置:首页 > 其它

PAT 1010. Radix (25)

2015-05-18 21:07 537 查看
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


这道题要注意的点,首先是,long int根本不够看,要用long long int来存储。然后题目虽然说每一位最多用z来表示,但这并不意味着radix最多为36. 这两个问题解决了以后,就只剩三个点没过了,其中两个点是答案错误,另一个点是运行超时。

先不管运行超时,仔细考量下题目,发现原先的代码存在这样一种情况:经过计算转化成十进制后两个数相等,然而推算出来的radix实际上小于某一位上的Digit。例如,推算出来radix=3时两个数字是相等的,然而在N1或N2的某一位上存在着字母a!

于是再加上一个判断,判断出radix最小可以是几,然后再进行计算。这样一来,所有的答案都正确了,但是还有一个点是运行超时的。要考虑一下如何优化算法。

想到加上二分法应该就可以避免超时了,一试之下果然通过了原先运行超时的点。然而第一个点却报出了答案错误,猜测是因为我设置的radix的上界比第一个点的答案要小了。怎么办呢,既然要判断两个数是否相等,那么把第一个数的值+1作为第二个数的radix的上界肯定是足够大了(因为题目中说取最小的符合要求的radix)。然后终于通过了所有的点,代码如下:

#include <iostream>
#include <string>
using namespace std;
long long int NtoTen(string target,long long int radix)
{
long long int result=0;
long long int pow=1;
int i,digit;
for(i=target.size()-1;i>=0;i--)
{
if(target[i]>='0'&&target[i]<='9')
digit=target[i]-'0';
else
digit=target[i]-'a'+10;

result+=digit*pow;
if(result<0)
return -1;
pow*=radix;
}
return result;
}
long long int minRadix(string target)
{
long long int result=0;
long long int radix=0;
int i,digit;
for(i=target.size()-1;i>=0;i--)
{
if(target[i]>='0'&&target[i]<='9')
digit=target[i]-'0';
else
digit=target[i]-'a'+10;
if(digit>radix)
radix=digit;
}
return radix+1;

}
int main(void)
{
string N1,N2;
int tag,i;
string src,target;
long long int result1,result2,radix,min,max,avg;
cin>>N1>>N2>>tag>>radix;
if(tag==1)
{
src=N1;
target=N2;
}
else
{
src=N2;
target=N1;
}
result1=NtoTen(src,radix);
min=minRadix(target);
max=result1+1;
for(;;)
{
avg=(min+max)/2;
result2=NtoTen(target,avg);
if(result2==-1||result2>result1)
max=avg-1;
else if(result1>result2)
min=avg+1;
else if(result1==result2)
{
cout<<avg;
return 0;
}
if(min>max)
break;
}
cout<<"Impossible";
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: