【二分法】PAT 1010 Radix

 

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

坑點:
1. 最大的進制的可能值不是36,而是max(l, res1)。
2. long long int類型在程序中很容易和int弄混,一定要一以貫之。
一些邊緣測試數據:
0 0 1 100  
12 c 1 10

#include<stdio.h>
#include<iostream>
#include<map>
using namespace std;
typedef long long int ll;
ll toD(string n, ll radix){
    ll sum = 0;
    ll temp = radix;
    for(int i = n.length()-1; i >= 0; i--){
        int t;
        if(n[i] >= '0' && n[i] <= '9') t = n[i]-'0';
        else t = n[i]-'a' + 10;
        if(i == n.length()-1) sum += t;
        else{
            sum += t * temp;
            temp *= radix;
        }
        //if(sum < 0) return -1;
    }
    return sum;
}
ll toR(string n){
    map<char, ll> mp;
    for(int i = 0; i <= 9; i++)
        mp[48+i] = i+1;
    for(int i = 0; i <= 26; i++){
        mp[97+i] = 11+i;
    }
    ll maxr = 1;
    for(int i = 0; i < n.length(); i++){
        maxr = max(maxr, mp[n[i]]);
    }
    return max(ll(2), maxr);
}
void solve(string n1, string n2, ll radix){
    ll res1 = toD(n1, radix), res2;
    ll l = toR(n2), r = max(res1, l);
    while(l <= r){
        ll mid = (l+r)/2;
        res2 = toD(n2, mid);
        if(res2 < 0 || res2 > res1) r = mid-1;
        else if(res2 == res1){
            printf("%lld", mid);
            return ;
        }
        else l = mid+1;
    }
    printf("Impossible");
}

int main(){
    string n1, n2;
    int tag;
    ll radix;
    cin >> n1 >> n2 >> tag >> radix;
    if(tag == 1) solve(n1, n2, radix);
    else solve(n2, n1, radix);

    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章