PAT甲级1010 Radix

题目描述:
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 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

题目大意:
给出四个数n1,n2,tag,radix,tag=1,那么radix代表n1的进制数,否则radix代表n2的进制数。已知其中一个的进制数,判断另一个数是不是该数某一个进制下的数(都将他们转化为10进制数,看是否相等,相等就是存在某一个进制),打印进制数。

代码如下:

#include <iostream>
#include <cmath>
#include<cctype>
#include <algorithm>
using namespace std;
long ToDecimal(long a,string s)
{
    long sum=0,k=s.size()-1;
    for(int i=0;i<s.size();i++,k--){
        if(isdigit(s[i]))sum+=int(s[i]-'0')*pow(a,k);
        else sum+=int(s[i]-'a'+10)*pow(a,k);
    }
    return sum;
}
long find_radix(string n,long a)
{
    char it=*max_element(n.begin(),n.end());
    long low=(isdigit(it)?it-'0':it-'a'+10)+1;
    long high=max(a,low);
    while(low<=high){
        long mid=(low+high)/2;
        long s=ToDecimal(mid,n);
        if(s==a) return mid;
        else if(s>a||s<0) high=mid-1;
        else low=mid+1;
    }
    return -1;
}
int main()
{
    string n1,n2;
    long tag,radix,m,k;
    cin>>n1>>n2>>tag>>radix;
    k=tag==1?find_radix(n2,ToDecimal(radix,n1)):find_radix(n1,ToDecimal(radix,n2));
    if(k!=-1) cout<<k;
    else cout<<"Impossible";
    return 0;
}

来总结一下:
1)这个题不能用暴力遍历的方法,测试点7会超时。。。所以只能用二分法!
2)用二分法就要涉及到上界和下界的问题,下界比较容易,就是n2中的最大数+1,上界不是很好想,是n1在十进制中的数(tag=1)。无法说的很清,这个问题保留吧先。
3)溢出问题,当转化的数存不下时,就会溢出,所以,在判断的时候应该是s>a||s<0。
4)说一说max_element()的使用方法。
首先它是在头文件< algorithm >中,而且返回的是迭代器。所以要加*,取出来的是最大值。

猜你喜欢

转载自blog.csdn.net/sun9979/article/details/84989259