问题
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<iostream>
#include<math.h>
#include<algorithm>
#include<string>
using namespace std;
long long convert(string s, long long radix)
{
long long sum = 0, tmp=0,index=0;
for (auto it = s.rbegin(); it != s.rend(); it++)
{
tmp = isdigit(*it) ? *it - '0' : *it - 'a' + 10;
sum += tmp*pow(radix, index);
index++;
}
return sum;
}
long long Radix(string s, long long num)
{
char it = *max_element(s.begin(), s.end());
long long low = isdigit(it) ? it - '0' + 1 : it - 'a' + 11;
long long high = num > low ? num : low;
while (low <= high)
{
long long mid = (low + high) / 2;
long long tmp = convert(s, mid);
if (tmp<0 || tmp>num) high=mid-1;
else if (tmp == num) return mid;
else low = mid + 1;
}
return -1;
}
int main()
{
string n1, n2;
long long tag, radix, num = 0,result=0;
cin >>n1>>n2>> tag >> radix;
if (tag == 1)
{
num = convert(n1, radix);
result = Radix(n2, num);
if (result == -1) printf("Impossible");
else printf("%lld", result);
}
else
{
num = convert(n2, radix);
result = Radix(n1, num);
if (result == -1) printf("Impossible");
else printf("%lld", result);
}
return 0;
}
后记
这个本来应该是昨天的任务,然后昨天身体不舒服。所以今天收尾,果然是脑袋不清醒的时候,干啥啥翻车。
这道题是参考的柳神的思路,不能算是自己独立写出来的。