这题的题意极难懂,给两个数a,b和a的进制x,问b在哪个进制下和x进制的a相等,一开始我以为就是简单的最高进制单字符为z=36就行了,后来发现不对,这题的基数可以非常大,比如999999 1 1 10这种情况,b的基数就可以取999999,可以看出基数最大的可能也就是a的十进制表示,还要注意用long long,而且求a的十进制表示时还有可能溢出,所以最后二分的时候还要讨论一下,总之坑太多了。
还有我一开始用itoa做的发现老是CE,后来才知道itoa是不能在g++中使用的。
#include<string>
#include<cstdlib>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<cstdlib>
#include<algorithm>
#include<functional>
#include<iostream>
using namespace std;map<char, int> ch;void init() {for (char c = '0'; c <= '9'; c++)ch[c] = c - '0';for (char c = 'a'; c <= 'z'; c++)ch[c] = c - 'a' + 10;
}long long convert(string know,long long bit) {long long sum = 0;long long radix = 1;for (int i = know.length() - 1; i >= 0; i--) {sum += ch[know[i]] * radix;radix *= bit;}return sum;
}
long long find_radix(string unknown, long long num) {char c = *max_element(unknown.begin(), unknown.end());//找到最大值long long left = ch[c]+1;long long right = max(num,left);while (left <= right) {long long mid = (left + right) / 2;long long t = convert(unknown, mid);if (t == num) return mid;else if (t<0||t > num) right = mid - 1;else left = mid + 1;}return -1;
}int main() {string n1, n2;long long tag, radix,result;init();cin >> n1 >> n2 >> tag >> radix;if (tag == 1)result = find_radix(n2, convert(n1, radix));elseresult = find_radix(n1, convert(n2, radix));if (result != -1)cout << result;elsecout << "Impossible";return 0;
}