您的位置:首页 > 其它

【USACO】1010. Radix (25)

2018-03-23 18:35 375 查看

题目描述:

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.

翻译:给一组正整数,例如,6和110,可以使等式6=110成立吗?答案是肯定的,如果6是一个十进制数并且110是一个二进制数的话。现在对于任意一对正整数N1、N2,你的任务是找到数字的进制,另一个已给出。

INPUT FORMAT

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.

翻译:每个输入文件包括一组输入数据。每组数据为一行包含4个正整数:N1,N2,tag,radix。这里N1和N2每个都不超过10个数字。每个数字都小于它的进制并且每个数字都在 {0-9, a-z} 范围内,0-9就代表数字0-9,a-z代表数字10-35。最后的数字“radix”是N1的进制如果“tag”为1,否则为N2进制。

OUTPUT FORMAT

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.

翻译:对于每组测试数据,在一行内输出可以使两个数字相等的另一个数字的进制。如果无法相等,则输出 “Impossible”。如果结果不唯一,输出最小的可能进制。

Sample Input 1:

6 110 1 10

Sample Output 1:

2

Sample Input 2:

1 ab 1 2

Sample Output 2:

Impossible

解题思路:

这道题主要问题是没给范围,我一开始认为数据在整数范围内,一直错误。。。。然后看了其他人的题解才发现需要用long long 保存。由于数据范围极大,所以要用二分搜索搜索结果。搜索下界为需要查找的数组中最大的值+1,上界为给出的数组的十进制数+1。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<algorithm>
#define INF 99999999
using namespace std;
char N[2][15];
long long int a=0,l[2];
int Min=0,tag,radix;
long long int test(long long int p){
long long int b=0,exp=1;
long long int temp=0;
if(tag==1)temp=1;
else temp=0;
for(long long int i=l[temp]-1;i>=0;i--){
b+=N[temp][i]*exp,exp*=p;
if(b<0)return -1;
}
return b;
}
int main(){
scanf("%s%s%d%d",N[0],N[1],&tag,&radix);
l[0]=strlen(N[0]),l[1]=strlen(N[1]);
for(int i=0;i<l[0];i++){
if(N[0][i]>='a'&&N[0][i]<='z')N[0][i]=N[0][i]-'a'+10;
else N[0][i]-='0';
if(tag!=1)Min=max(Min,(int)N[0][i]);
}
for(int i=0;i<l[1];i++){
if(N[1][i]>='a'&&N[1][i]<='z')N[1][i]=N[1][i]-'a'+10;
else N[1][i]-='0';
if(tag!=2)Min=max(Min,(int)N[1][i]);
}
long long exp=1;
if(tag==1)for(int i=l[0]-1;i>=0;i--)a+=N[0][i]*exp,exp*=radix;
else      for(int i=l[1]-1;i>=0;i--)a+=N[1][i]*exp,exp*=radix;
int flag=0;
long long pre=Min+1,pro=a+1,ans=0,t;
while(pre<=pro){
long long int temp=(pre+pro)/2;
if(flag)break;
t=test(temp);
if(t==a){
if(ans==0)ans=temp;
else ans=min(ans,temp);
pro=temp-1;
flag=1;
}
else if(t>a||t<0){
pro=temp-1;
}
else if(t<a){
pre=temp+1;
}
}
if(ans)printf("%lld\n",ans);
else printf("Impossible\n");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 PAT 甲级