题干:
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
题目大意:
给定两个字符串,每个都是0~9 , a~z 代表0~35这36个数字。
给定一个数字的radix,你的任务是找到另一个数字的基数,使得N1=N2。
解题报告:
我们知道,把十进制数转化成其他进制是困难的,但是把其他进制转化成十进制是较为简单的。所以直接锁定一个目标进制之后,转化成十进制比较两个数字式是否相同就可以了。刚开始想错了,以为就是最多就是35进制了,但是其实则不然,可以是无穷进制,所以不能直接枚举了。考虑到上界是比较好确定的,并且随着radix的增大,转化的十进制数是单调递增的,考虑二分。
注意二分的上下界限制就好了。
AC代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<set>
#include<string>
#include<cmath>
#include<cstring>
#define FF first
#define SS second
#define ll long long
#define pb push_back
#define pm make_pair
using namespace std;
typedef pair<int,int> PII;
const int MAX = 2e5 + 5;
char n1[MAX],n2[MAX],ned[MAX];
int tag,radix;
__int128 shi;
int go(char c) {if(c >= '0' && c <= '9') return c - '0';else return c - 'a' + 10;
}
__int128 trans(char s[],ll rdx) {//把s从rdx进制转化成10进制 __int128 res = 0;int len = strlen(s);for(int i = 0; i<len; i++) {res = res * rdx + go(s[i]);if(res < 0) return (__int128)9e18 * 2;}return res;
}int main()
{cin>>n1>>n2>>tag>>radix;if(tag == 1) shi = trans(n1,radix),strcpy(ned,n2);else shi = trans(n2,radix),strcpy(ned,n1);int mx = 0,len = strlen(ned);for(int i = 0; i<len; i++) {mx = max(mx,go(ned[i]));}__int128 l = mx+1,r = 9e18,mid;ll ans=-1;while(l<=r) {mid = (l+r)>>1;__int128 tmp = trans(ned,mid); if(tmp < shi) l = mid+1;else r = mid-1;if(tmp == shi) ans = mid;}if(ans != -1) printf("%lld\n",ans);else printf("Impossible\n");return 0 ;
}