您的位置:首页 > 其它

1010. Radix (25)(PAT甲)

2017-05-28 08:55 344 查看
Radix (25)

时间限制

400 ms

内存限制

65536 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<cstring>
#include<string>
#include<cstdio>
#include<algorithm>
using namespace std;
#define INF  0x3f3f3f3f
#define N 100005
#define LL long long int
//如果两个数都是一位,就有点意思了,值就是自己的值,是永远小于进制的
//如果两个数都是多位,就有了有多种进制的可能,便可以加以考虑
LL getNum(char s[], LL jinzhi)
{
int len = strlen(s);

LL total = 0;
LL xi = 1;
for (int i = len - 1; i >= 0; i--)
{
int num = 0;
if (s[i] >= '0' && s[i] <= '9')
{
num = s[i] - '0';
}
if (s[i] >= 'a' && s[i] <= 'z')
{
num = s[i] - 'a' + 10;
}

total += (LL)num * xi;
xi *= jinzhi;
}
return total;
}

int main()
{
char N1[11];
char N2[11];
int tag;
LL radix;
while (scanf("%s%s%d%lld", N1, N2, &tag, &radix) != EOF)
{
char str[11];
LL total = 0;
if (tag == 1)
{
total = getNum(N1, radix);
strcpy(str, N2);
}
if (tag == 2)
{
total = getNum(N2, radix);
strcpy(str, N1);
}
if (total < 0)
{
printf("Impossible\n");
continue;
}

int maxC = 0;
int len = strlen(str);
for (int i = 0; i<len; i++)
{
int num = 0;
if (str[i] >= '0' && str[i] <= '9')
{
num = str[i] - '0';
}
if (str[i] >= 'a' && str[i] <= 'z')
{
num = str[i] - 'a' + 10;
}
if (num > maxC)
{
maxC = num;
}
}

LL minRadix = (LL)(maxC + 1);
LL maxRadix = total + 1;

LL ans = -1;
while (minRadix <= maxRadix)
{
LL mid = (maxRadix - minRadix) / 2 + minRadix;
LL nowNum = getNum(str, mid);
if (nowNum == total)
{
ans = mid;
break;
}
else if (nowNum > total || nowNum < 0)
{
maxRadix = mid - 1;
}
else {
minRadix = mid + 1;
}
}
if (ans == -1)
{
printf("Impossible");
}
else {
while (getNum(str, ans) == total && ans >= minRadix)
ans--;
printf("%d", ans + 1);
}
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: