PAT甲级1010 Radix/acwing1482. 进制
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 N 1and N 2, 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
给定一对正整数,例如 6 和 110,此等式 6=110 是否成立?
答案是可以成立,当 6 是十进制数字,110 是二进制数字时等式得到满足。
现在,给定一个正整数数对 N1,N2,并给出其中一个数字的进制,请你求出另一个数字在什么进制下,两数相等成立。
输入格式
输入共一行,包含四个正整数,格式如下:
N1 N2 tag radix
N1 和 N2 是两个不超过 10 位的数字,radix 是其中一个数字的进制,如果 tag 为 1,则 radix 是 N1 的进制,如果 tag 为 2,则 radix 是 N2 的进制。
注意,一个数字的各个位上的数都不会超过它的进制,我们用 0∼9 表示数字 0∼9,用 a∼z 表示 10∼35。
输出格式
输出使得 N1=N2 成立的另一个数字的进制数。
如果等式不可能成立,则输出 Impossible。
如果答案不唯一,则输出更小的进制数。
数据范围
2≤radix≤36
输入样例1:
6 110 1 10
输出样例1:
2
输入样例2:
1 ab 1 2
输出样例2:
Impossible
先求给定数在十进制下的值target,所求进制最大为target+1,0<target<1e16,longlong存得下,用二分做不会超时
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int get(char c)
{
if (c<='9') return c-'0';
else return c-'a'+10;
}
LL get_num(string s,LL r){
LL ans=0;
for(char c:s){
if((double)ans*r+get(c)>1e16) return 1e18;
ans=ans*r+get(c);
}//秦九昭算法四行,朴素算法十多行还要特判
/*int cnt=0;
LL base=1;
reverse(s.begin(),s.end());
for(char c:s){
cnt++;
if(cnt>1){
if((double)base*r>=1e16) return 1e18;
base*=r;
}
if(ans+(double)base*(get(c))>=1e16) return 1e18;
ans=ans+base*(get(c));
}
*/
return ans;
}
int main(){
char maxc;
string a,b;
LL idx,rdx,i,j;
cin>>a>>b>>idx>>rdx;
if(idx!=1) swap(a,b);
LL target=get_num(a,rdx);
j=target+1;//二分上界
for(char c:b) if(c>maxc) maxc=c;
i=get(maxc)+1;//二分下界
while(i<j){//二分
LL mid=i+j>>1;
//cout<<mid<<endl;
if(get_num(b,mid)>=target) j=mid;
else i=mid+1;
}
if(get_num(b,i)==target) cout<<i;
else cout<<"Impossible";
return 0;
}