题目地址

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

作者: CHEN, Yue
单位: 浙江大学
时间限制: 400 ms
内存限制: 64 MB

#include <iostream>            //未AC
#include <vector>
#include<algorithm>
#include <cmath>
#include<map>           //要改unordered;
#include<string>
#include<set>
using namespace std;
void to_arr(string a,vector<int> &v){
    for(int i=0;i<a.length();i++){
        if(a[i]>='0'&&a[i]<='9')
        v.push_back(a[i]-'0');
        else v.push_back(a[i]-'a'+10);
    }
}
long long to_dec(vector<int> &v,int radix){
    int n=0;
    for(int i=0;i<v.size();i++){
        n+=v[i]*pow(radix,v.size()-1-i);
    }
    return n;
}
int main(){
    string a,b;int tag,radix;
    cin>>a>>b>>tag>>radix;
    if(tag==2) swap(a,b);
    vector<int> v1,v2;
    to_arr(a,v1);
    to_arr(b,v2);
    long long n1=to_dec(v1,radix),i;
    for( i=2;i<1000;i++){
        long long n2=to_dec(v2,i);
        if(n1==n2) break;
    }
    if(i!=1000) cout<<i;
    else cout<<"Impossible";
}