【PAT 甲级】1010 Radix (25)(二分法)

题目链接

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

题意:给定N1、N2两个数字,tag==1时,radix是N1的进制数,否则是N2的进制数,要求找到让两个数字相等的进制。

思路:先将两个数字转化为10进制数。再用二分法,寻找让N1、N2相等的进制

代码:

#include <iostream>
#include <sstream>
#include <string>
#include <cstdio>
#include <queue>
#include <cstring>
#include <map>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N = 1e5+5;
const ll INF = 0x3f3f3f3f;
const double eps=1e-4;
const int T=3;

ll convert(string str,ll radix) {
    ll res=0;
    int k=0,tmp=0;
    for(auto it=str.rbegin(); it!=str.rend(); it++) {
        tmp=isdigit((*it))?*it-'0':*it-'a'+10;
        res+=tmp*pow(radix,k++);
    }
    return res;
}
ll solve(string str,ll num) {
    ///取字符串str中最大的一位字符
    char ch=*max_element(str.begin(),str.end());
    ll lb=(isdigit(ch)?(ch-'0'):(ch-'a'+10))+1;
    ll rb=max(num,lb),mid;
    while(lb<=rb) {
        mid=(lb+rb)>>1;
        ll tmp=convert(str,mid);
        if(tmp<0||tmp>num)
            rb=mid-1;
        else if(tmp==num)
            return mid;
        else
            lb=mid+1;
    }
    return -1;
}
int main() {
    string str1,str2;
    ll ans,tag,radix;
    cin>>str1>>str2>>tag>>radix;
    if(tag==1) {
        ans=solve(str2,convert(str1,radix));
    } else {
        ans=solve(str1,convert(str2,radix));
    }
    if(ans==-1) {
        cout<<"Impossible";
    } else {
        cout<<ans;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/feng_zhiyu/article/details/81002066