【题解】PATA-1010 Radix

Radix(PATA-1010)

题面

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.

输入

Each input file contains one test case. Each case occupies a line which contains 4 positive integers:

1
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.

输出

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.

样例输入1

1
6 110 1 10

样例输出1

1
2

样例输入2

1
1 ab 1 2

样例输出2

1
Impossible

提示

思路

二分。

代码

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const int inf = 0x3f3f3f3f;
const int mxn = 1e6 + 5;

char a[mxn], b[mxn];

LL getnum(char *s, LL r){
LL ans = 0;
for(; *s; s++)
ans = ans * r + (*s - (*s <= '9' ? '0' : 'a'-10));
return ans;
}

LL getans(char *s, char *t, LL r){
char mx = *max_element(t, t+strlen(t));
LL l = mx - (mx <= '9' ? '0' : 'a'-10) + 1;
LL f=0, at = getnum(s, r); r = max(l, at);
while(l <= r){
LL m = (l + r) / 2;
LL bt = getnum(t, m);
if(bt < 0 || bt > at){
r = m - 1;
}else if(at == bt){
f = m;
break;
}else{
l = m + 1;
}
}
return f;
}

int main()
{
LL t, r;
scanf("%s %s %lld %lld", a, b, &t, &r);
LL f = (t==1) ? getans(a, b, r) : getans(b, a, r);
if(f){
printf("%lld\n", f);
}else{
printf("Impossible\n");
}

return 0;
}
_/_/_/_/_/ EOF _/_/_/_/_/