1010 Radix (25分)
作者:CHEN, Yue
单位:浙江大学
代码长度限制:16 KB
时间限制:400 ms
内存限制:64 MB
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,每一位用0-9和a-z表示0-35),给定两数中第fag个数的进制为radix,求另一个数的进制为多少时两数可以相等,否则输出“Impossible”。
思路:
1.首先,先将给定的那个数转换成10进制,由于长度为10,在转换为10进制数时选取long long
不然会出问题;
2.其次,要求的另一个数的进制并非是2-36进制,可以很大,如53进制等,其进制数肯定介于另一个数的十进制值与该数最大位值之间,若用遍历,程序超时,所以选取二分法(这题试了好多好多遍)
参考代码:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
long long ans_fag,ans_obj,fag,radix,obj_radix;
long long strtoint(string str,long long radix){
long long sum=0;
for(int i=0;i<str.length();i++){
int num=str[i]<='9'?str[i]-'0':str[i]-'a'+10;
sum=sum*radix+num;
}
return sum;
}
long long find_radix(string str){
char maxstr=*max_element(str.begin(),str.end());
long long low=maxstr<='9'?maxstr-'0'+1:maxstr-'a'+11;
long long high=max(ans_fag,low);
while(low<=high){
long long mid=(low+high)/2;
ans_obj=strtoint(str,mid);
if(ans_obj<0||ans_obj>ans_fag)high=mid-1;
else if(ans_fag==ans_obj)return mid;
else low=mid+1;
}
return -1;
}
int main() {
string str[3];
cin>>str[1]>>str[2]>>fag>>radix;
int obj=fag==1?2:1;
ans_fag=strtoint(str[fag],radix);
obj_radix=find_radix(str[obj]);
if(obj_radix!=-1)cout<<obj_radix<<endl;
else cout<<"Impossible"<<endl;
return 0;
}
如有错误,欢迎指正