您的位置:首页 > 其它

PAT 1010. Radix (25)

2014-07-07 20:54 357 查看
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

题目坑挖的比较多,首先输入数据不超过10位,但是数据的值可能爆32位,需要注意。

其次进制范围没有限定,这表示进制可能很大。

基本思想就是遍历进制。鉴于进制太大,进行二分,防止超时。

如果满足条件的进制不唯一,要求输出最小的进制这点需要认真考虑下,结果是个位数可能出现此情形。

解决好以上几点,这题也就差不多了。



#include<stdio.h>
#include<math.h>
#include<string.h>
char val[128];
int max=0;
long long  to10(char n[],int radix)
{
long long sum=0;
int i=0,len=strlen(n);
for(;i<len;i++)
{
sum=sum*radix+val[n[i]];
if(sum<0)break;
}
return sum;
}
int main()
{
int x=0;
for(x=48;x<58;x++)val[x]=x-48;
for(x=65;x<65+26;x++)val[x]=x-55;
for(x=97;x<97+26;x++)val[x]=x-87;
long long sum,sum1=0,sum2,sum3,i,k=20000000000;
char n[2][20];
int tag,radix;
scanf("%s%s%d%d",&n[0],&n[1],&tag,&radix);
for(x=0;x<strlen(n[2-tag]);x++)max=max>val[n[2-tag][x]]?max:val[n[2-tag][x]];
sum=to10(n[tag-1],radix);
i=max+1;
while(1)
{
sum1=to10(n[2-tag],i);
sum2=to10(n[2-tag],(k+i)/2);
if(sum1>sum||i>k)break;<span style="white-space:pre">	</span>
if(sum2==sum)
{
if(sum<10&&((i+k)/2>(sum+1)))
printf("%d\n",sum+1);
else
printf("%d\n",(i+k)/2);
return 0;
}
else if(sum2>sum||sum2<=0)
{
k=(i+k)/2-1;
}
else if(sum2<sum)
{
i=(i+k)/2+1;
}
}
printf("Impossible\n");
return 0;
}



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