这道题,本身倒没什么。需要注意几点。
1) 大数据,用long long而不是int,包括其中需要尝试的radix。这里吃了大亏
2) 多个进制选最小的情况,只能是输入数据为一位的情况。所以只需判断是不是一位。这里理解不够透彻
3) 溢出,尝试进制时,有产生负数的情况,要考虑到。
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <cmath>
using namespace std;
long long a;
string b;
map<char, int> nums;
void init()
{
for (int i = ‘0‘; i < ‘9‘ + 1; i++)
{
nums[i] = i - ‘0‘;
}
for (int i = ‘a‘; i < ‘z‘ + 1; i++)
{
nums[i] = i - ‘a‘ + 10;
}
}
void in()
{
//ifstream cin("in.txt");
string num_a, num_b, src;
cin >> num_a >> num_b;
long long order, radix;
cin >> order >> radix;
if (order == 1)
{
b = num_b;
src = num_a;
}
else
{
b = num_a;
src = num_b;
}
for (int i = 0; i < src.size(); i++)
{
char ch = src[i];
a = a * radix + nums[ch];
}
}
long long solve()
{
long long p = -1;
long long q;
long long temp = 0;
long long ret = -1;
for (int i = 0; i<b.size(); i++)
{
char ch = b[i];
if (nums[ch]>p)
{
p = nums[ch];
}
}
p++;
if (b.size() == 1 && a == nums[b[0]])
{
return p;
}
q = pow((double)a / nums[b[0]], 1.0 / (b.size() - 1));
while (p <= q)
{
long long mid = (p + q) / 2;
temp = 0;
for (int i = 0; i < b.size(); i++)
{
char ch = b[i];
temp = temp * mid + nums[ch];
}
if (temp == a)
{
ret = mid;
break;
}
else if (temp>a || temp<0)
{
q = mid - 1;
}
else
{
p = mid + 1;
}
}
return ret;
}
int main(int argc, char **argv)
{
init();
in();
long long ret = solve();
if (ret > 0)
{
cout << ret << endl;
}
else
{
cout << "Impossible\n";
}
return 0;
}