PAT(Advanced Level) 1010 - Radix(二分)

    xiaoxiao2021-08-17  122

    *1010. 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

    题意: 给出两个数,和一种进制,问是否能用另一种进制表示一个数,使得这两种进制的数的数值相等。

    解题思路: 二分。最小的进制是第二种里出现的最大的数。最大的进制是第一个数的数值。 这里要注意,他没说这个进制的上限,所以计算过程中这个数值可能会比较大。 这里用long long 也是不可以的,要用unsigned long long.

    AC代码:

    #include<bits/stdc++.h> using namespace std; unsigned long long get(char a) { if(a >= '0' && a <= '9') return a-'0'; return a-'a'+10; } int main() { string n1,n2; unsigned long long tag,radix; cin>>n1>>n2>>tag>>radix; if(tag == 2) swap(n1,n2); unsigned long long r = 0; for(unsigned long long i = 0;n1[i];i++) r = r*radix+get(n1[i]); unsigned long long ans = r; unsigned long long l = 0; for(unsigned long long i = 0;n2[i];i++) l = max(l,get(n2[i])); unsigned long long res = 0; l++,r++; while(l <= r) { unsigned long long mid = (l+r)>>1; unsigned long long check = 0; for(unsigned long long i = 0;n2[i];i++) check = check*mid + get(n2[i]); if(check == ans) res = mid; if(check >= ans) r = mid-1;else l = mid+1; } res?cout<<res:cout<<"Impossible"; return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-676522.html

    最新回复(0)