【PAT - 甲级1010】Radix (25分)(二分,进制转化)
題干:
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?N?1???and?N?2??, 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 radixHere?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 10Sample Output 1:
2Sample Input 2:
1 ab 1 2Sample Output 2:
Impossible題目大意:
給定兩個字符串,每個都是0~9 ,?a~z 代表0~35這36個數(shù)字。
給定一個數(shù)字的radix,你的任務是找到另一個數(shù)字的基數(shù),使得N1=N2。
解題報告:
我們知道,把十進制數(shù)轉(zhuǎn)化成其他進制是困難的,但是把其他進制轉(zhuǎn)化成十進制是較為簡單的。所以直接鎖定一個目標進制之后,轉(zhuǎn)化成十進制比較兩個數(shù)字式是否相同就可以了。剛開始想錯了,以為就是最多就是35進制了,但是其實則不然,可以是無窮進制,所以不能直接枚舉了??紤]到上界是比較好確定的,并且隨著radix的增大,轉(zhuǎn)化的十進制數(shù)是單調(diào)遞增的,考慮二分。
注意二分的上下界限制就好了。
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進制轉(zhuǎn)化成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 ; }?
總結(jié)
以上是生活随笔為你收集整理的【PAT - 甲级1010】Radix (25分)(二分,进制转化)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2017年中信银行微信申请信用卡秒批方法
- 下一篇: fmc是fpga直接引出来的吗_家长速看