PAT(Advance Level) 1010 Radix (25 分)

Describe

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​1 and 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

std

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

ll to_dec(string str,int radix){
    ll res = 0;
    for(int i = 0 ; i < str.length(); ++i){
        if(str[i]=='-') continue;
        if(str[i] >= '0' && str[i] <= '9')
            res = res * radix + str[i] - '0';
        else 
            res = res * radix + str[i]-'a' + 10;
    }
    if(str[0] == '-') res *= -1;
    return res;
}
int binary_find(string str,ll num){
    char it = *max_element(str.begin(), str.end());
    ll low = (isdigit(it) ? it - '0' : it - 'a' + 10) + 1;
    ll high = max(num, low);
    while(low <= high){
        ll mid = (low + high) >> 1;
        ll temp = to_dec(str, mid);
        if(temp < 0 || temp > num) high = mid - 1;
        else if(temp == num) return mid; 
        else low = mid + 1;
    }
    return -1;
}
int main(){
    string n1, n2;
    int tag, radix;
    cin >> n1 >> n2 >> tag >> radix;
    if(tag == 2) swap(n1,n2);
    int  res_tag = binary_find(n2,to_dec(n1, radix));
    if(res_tag == -1) cout << "Impossible";
    else cout << res_tag;
    return 0;
}
文章名: 《PAT(Advance Level) 1010 Radix (25 分)》
文章链接:http://hrhr7.cn/index.php/archives/21/
联系方式:tensor7@163.com
除特别注明外,文章均为Cupidr原创,转载时请注明本文出处及文章链接
Last modification:November 22nd, 2019 at 08:02 pm
如果觉得我的文章对你有用,请随意赞赏

Leave a Comment