PAT 1010. Radix (25) 变态题,各种坑点

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
 
  
各种坑点。不想说话。注意爆栈是怎么处理的,注意二分法的上下界是怎么处理的。而且一定要注意要用getnum2,不能用getnum1。
个人猜测是因为getnum2爆栈的话爆的是sum,sum会正确的变负数。而getnum1的话,k爆栈后下一次sum+=k*a[i]可能还是正数,这就不对了。
 
  
 
  
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include<string>
#include<string.h>
using namespace std;


long long getnum1(int radix,string a)
{
    long long sum=0;
    int k=1;
    for(int i=a.size()-1;i>=0;i--)
    {
        if(a[i]<='9'&&a[i]>='0')
           sum+=k*(a[i]-'0');
         else sum+=k*(a[i]-'a'+10);
        k*=radix;
    }
    return sum;
}

long long getnum2(int radix,string a)
{
    long long sum=0;
    for(int i=0;i<a.size();i++)
    if(a[i]<='9'&&a[i]>='0')
    sum=sum*radix+(a[i]-'0');
    else sum=sum*radix+(a[i]-'a'+10);

    return sum;
}

long long getminn(string s)
{
    int maa=-1;
    for(int i=0;i<s.size();i++)
    {
        if(s[i]<='9'&&s[i]>='0'&&(s[i]-'0')>maa  )
         maa=s[i]-'0';

        if(s[i]<='z'&&s[i]>='a'&&(s[i]-'a'+10)>maa )
        maa=s[i]-'a'+10;
    }

    return maa+1;

}

int main()
{
    string a,b;
    cin>>a>>b;
    long long tag,radix;
    cin>>tag>>radix;
    if(tag==2) swap(a,b);
    long long target=getnum2(radix,a);
    long long head=getminn(b);
    long long tail=target+1;
    long long now;
    int flag=0;
    long long minn;
    while(head<=tail)
    {
        now=(head+tail)/2;
        long long  zz=getnum2(now,b);

        if(zz>target||zz<=0)
        {
            tail=now-1;
        }
        else  if(zz<target)
        {
            head=now+1;
        }
        else
        {
           flag=1;
           break;
        }
    }
     if(flag==0) cout<<"Impossible";
     else cout<<now;

   return 0;
}


猜你喜欢

转载自blog.csdn.net/yxpandjay/article/details/78005882
今日推荐