PAT-1010. Radix (25)

来源:互联网 发布:特征向量组成的矩阵 编辑:程序博客网 时间:2024/06/10 01:52

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


提交代码


题目刚看起来很简单,但是坑特别特别多,不知道中坑的有多少


#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#include <string>#include <cmath>using namespace std;int tag;string a[3];long long r;//题目中没有给定r的范围 long long trans(string s,int radix){long long mul=1,ans=0;for(int i=0;i<s.length();i++){int j=s.length()-1-i;if(s[j]>='0'&&s[j]<='9')ans+=(s[j]-'0')*mul;else ans+=(s[j]-'a'+10)*mul;mul*=radix;}return ans;}int cmp(string s,int radix,int num1){long long mul=1,ans=0;for(int i=0;i<s.length();i++){int j=s.length()-1-i;if(s[j]>='0'&&s[j]<='9')ans+=(s[j]-'0')*mul;else ans+=(s[j]-'a'+10)*mul;mul*=radix;if(ans>num1) return 1;}if(ans==num1) return 0;return -1;}int maxNum(string s){int ans=0;for(int i=0;i<s.length();i++){int num;if(s[i]>='0'&&s[i]<='9') num=s[i]-'0';else num=s[i]-'a'+10;if(num>ans) ans=num;}return ans;}long long binarySearch(int cur,int num1){long long l=maxNum(a[cur])+1,r=(num1>=l)?num1:l,m;//下界最大数字位+1 ,上届应该是num1,这里的上届也要格外注意!!!!! int flag=-1;while(l<=r){m=(l+r)/2;int temp=cmp(a[cur],m,num1);if(temp==0) return m;else if(temp==1) r=m-1;else l=m+1;}return flag;}int main(){while(cin >> a[1] >> a[2] >> tag >> r){if(a[1]=="1"&&a[2]=="1")//题目中要求的按从小规则 {cout << "2" << endl;continue;} if(a[1]==a[2]){cout << r << endl;continue;}long long temp=trans(a[tag],r);int cur=(tag==1)?2:1;long long res=binarySearch(cur,temp); if(res==-1)cout << "Impossible" << endl;else cout << res << endl;}return 0;}