您的位置:首页 > 其它

1010. Radix (25)——PAT (Advanced Level) Practise

2014-09-24 09:20 525 查看
题目信息:


1010. Radix (25)

时间限制

400 ms

内存限制

32000 kB

代码长度限制

16000 B

判题程序

Standard

作者

CHEN, Yue

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 <algorithm>
#include <string>
using namespace std;

long long strtol(string &str, long long rdx)
{
long long re = 0;
long long n = 1;
char ch;
int t;
for (int i = str.size() - 1; i >= 0; i--)
{
ch = str[i];
if (ch <= '9')
t = ch - '0';
else
t = ch - 'a' + 10;
re += t * n;
n *= rdx;
}
return re;
}
int cmp(string str, long long rdx, long long n1)
{
long long sum = 0;
long long n = 1;
char ch;
int t;
for (int i = str.size() - 1; i >= 0; i--)
{
ch = str[i];
if (ch <= '9')
t = ch - '0';
else
t = ch - 'a' + 10;
sum += t * n;
n *= rdx;
if (sum > n1)
return 1;
}
if (sum < n1)
return -1;
else if (sum > n1)
return 1;
else
return 0;
}
long long binarysearch(string str, long long min, long long max, long long n)
{
long long mid = min;
while (min <= max)
{
int i = cmp(str, mid, n);
if (i == 0)
return mid;
else if (i == 1)
max = mid - 1;
else
min = mid + 1;
mid = (min + max) / 2;
}
return -1;
}
int main()
{
string str1, str2;
cin >> str1 >> str2;
long long i, radix;
cin >> i >> radix;
if (i == 2)
{
str1.swap(str2);
}
long long n1 = strtol(str1, radix);

if (n1 == 1 && str2 == "1") //这两条奇葩的条件!!
{
cout << "2" << endl;
return 0;
}
else if (str1 == str2)
{
cout << radix << endl;
return 0;
}

char crds = *max_element(str2.begin(), str2.end());
int redx;
if (crds <= '9')
redx = crds - '0' + 1;
else
redx = crds - 'a' + 10 + 1;
int dx = (redx > n1) ? redx : n1 ;
i = binarysearch(str2, redx, dx, n1);
if (i == -1)
cout << "Impossible" << endl;
else
cout << i << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: