1010 Radix

1010 Radix
分数 25

全屏浏览

切换布局
作者 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 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 radixHere 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.分析

        1.确定一个数的进制后算出其的十进制形式

        2.找出不确定进制的最低进制(最大的单个数字加一)

        3.从第二步找出的最低进制向上找到符合的进制

        4.如果一个一个找即while(true) 会有一个测试点超时

        5.用二分,但是也会超出longlong范围,需要判断一下。

2.代码

#include
#include
using namespace std;
typedef long long LL;
string s1,s2;
LL a,b;
LL tag,radix,re;

LL check(string s,LL d){           //转换函数
    LL t=0;
    for(int i=s.size()-1;i>=0;i--){
        if(s[i]>='a'&&s[i]<='z'){
            t+=pow(d,s.size()-1-i)*(s[i]-'a'+10);
        }
        else t+=pow(d,s.size()-1-i)*(s[i]-'0');
    }
    return t;
}
int main(){
    cin>>s1>>s2;
    cin>>tag>>radix;
    if(tag==2){
        swap(s1,s2);
    }
    a=check(s1,radix);
    int ma=1;
    for(int i=0;i='a'&&s2[i]<='z'){
            ma=max(ma,s2[i]-'a'+10);
        }
        else ma=max(ma,s2[i]-'0');
    }
    ma++;
    LL l=ma,r=a+1;           //二分
    while(l<=r){
        LL mid=r+l>>1;
        LL t=check(s2,mid);
        if(t>a|| t <= 0) r=mid-1;     //判断是否溢出
        else if(t==a){
            cout<

你可能感兴趣的:(pta英文题,算法,数据结构)