1010. Radix

来源:互联网 发布:淘宝上的上海华硕商城 编辑:程序博客网 时间:2024/06/15 18:27
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

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <deque>
#include <queue>
#include <cstring>
#include <vector>
#include <string>
#include <iomanip>
#include <map>
#include <cmath>
#include <stack>
#include <algorithm>
using namespace std;
#define max1 16777217
#define inf 6000
long long fum(string a,long long b)
{
    int n=a.length();
    long long sum=0,num;
    for(int i=0;i<n;i++)
    {
        if('0'<=a[i]&&a[i]<='9')
            num=a[i]-'0';
        else
            num=a[i]-'a'+10;
        sum=sum*b+num;
    }
    return sum;
}
int FindRadix_Bottom(string a)
{
    bool flag[35];
    for(int i=0;i<36;i++)
        flag[i]=false;
    long long i=0;
    for(;i<a.length();i++)
    {
        if(a[i]>='0'&&a[i]<='9')
            flag[a[i]-'0']=true;
        else
            flag[a[i]-'a'+10] = true;
    }
    for(i=35;i>=0;i--)
    {
        if(flag[i])
            break;
    }
    return i+1;
}
long long find(long long low,long long num,string b)
{
    long long i,hight=num+1;
    long long num2;
    while(low<=hight)
    {
        i=(low+hight)/2;
        num2=fum(b,i);
        if(num2>num||num2<0)
            hight=i-1;
        else if(num2<num)
            low=i+1;
        else
            return i;
    }
    return -1;
}
int main()
{
    string a,b,f;
    int c;
    long long d,temp1,temp2,m;
    cin>>a>>b;
    cin>>c>>d;
    if(c==2)
    {
        f=a;
        a=b;
        b=f;
    }
    long long i;
    temp1=fum(a,d);
    m=FindRadix_Bottom(b);
    if(a==b)
    {
        if(temp1==0)
            cout<<"1"<<endl;
        else
            cout<<d<<endl;
        return 0;
    }
    long long h=find(m,temp1,b);
    if(h!=-1)
        cout<<h<<endl;
    else
        cout<<"Impossible";
    return 0;
}

0 0
原创粉丝点击