PAT甲级练习题- Radix (25) - 二分查找

1010. Radix (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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的进制
    = 2表示为n2的进制

题解:
最小的进制肯定是n1中最大的数位+1,
最大的进制却不是26,而是n1+1,表示n2用一位就能表示n1
所以不能用for循环枚举,而是用二分查找
注意数据范围要用long long
注意在x进制下n2可能溢出,这时应该将查找区域固定到左半边
*/

#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
typedef long long ll;
const int maxn = 2000+10;
const int INF = 0x3f3f3f3f;

ll change(char c){
    if(c >= '0' && c <= '9')
        return c-'0';
    else return c-'a'+10;
}

ll getval(string s,int x){///在x进制下 s转化为十进制的数值为
    ll res = 0;
    for(int i = 0;i<s.length();++i){
        res *= x;
        res += change(s[i]);
        if(res < 0) return -1;///这里注意res可能溢出
    }
    return res;

}

int main(){
    string n1,n2,t;
    int tag,radix;
    cin>> n1>>n2>>tag>>radix;
    if(tag == 2 ){ ///让n1总是表示参照的
        t = n1;
        n1 = n2;
        n2 = t;
    }
    ll n1val = getval(n1,radix);
    ll low = 0, high, mid;
    for(int i = 0;i<n2.length();++i){
        if(change(n2[i]) > low) low = change(n2[i]);
    }
    low++;
    high = n1val+1;

    bool f = 0;
    while(low <= high){
        mid = (low+high)/2;
        ll midval = getval(n2,mid);
        if(midval < 0 || midval > n1val)
            high = mid -1;
        else if(midval < n1val)
            low = mid +1;
        else if(midval = n1val) {
            f = 1;
            break;
        }
    }
    if(f) cout << mid;
    else cout<<"Impossible";

    return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值