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 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

代码参考柳神:

#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <string>
#include <cctype>
#include <string.h>
using namespace std;
long long radix(long long *a,long long rad,long long len){//转换为10进制
    long long sum=0;
    for(int i=0;i<len;i++)
        sum=a[i]+sum*rad;
    return sum;
}
long long bin(long long *a,long long left,long long right,long long len,long long x){//二分查找找进制
    long long mid,ans;
    while(left<=right){
        mid=(left+right)/2;
        ans=radix(a,mid,len);
        if(ans==x) return mid;
        else if(ans>x||ans<0) right=mid-1;
        else left=mid+1;
    }
    return 0;
}
int main(){
    string n1,n2;
    long long tag,rad,a[100],b[100],ans,len,low=0;
    cin>>n1>>n2>>tag>>rad;
    if(tag==2) swap(n1,n2);
    for(int i=0;i<n1.length();i++){
        if(isdigit(n1[i])) b[i]=n1[i]-'0';
        else b[i]=n1[i]-'a'+10;
    }
    ans=radix(b,rad,n1.length());
    len=n2.length();
    for(int i=0;i<len;i++){
        if(isdigit(n2[i])) a[i]=n2[i]-'0';
        else a[i]=n2[i]-'a'+10;
        low=low>a[i]?low:a[i];//确定最小进制
    }
    long long result=bin(a,low+1,ans+1,len,ans);
    if(result) printf("%lld\n",result);
    else printf("Impossible\n");
    return 0;
}





猜你喜欢

转载自blog.csdn.net/qq_42068614/article/details/86535492