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 1and 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
#include<cstdio>
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<map>
#include<cmath>
using namespace std;
typedef long long ll;
const ll inf=(1ll << 63)-1;
int chartoint(char ch){if(ch>='0'&&ch<='9') return ch-'0';else return ch-'a'+10;
}
ll converttoten(string str,ll radix){ll num=0;for(int i=0;i<str.size();i++){num=num*radix+chartoint(str[i]);}if(num<0||num>inf) return -1;return num;
}
int cmp(string n2,ll radix,ll num1){ll num2=converttoten(n2,radix);if(num2<0) return 1;if(num1>num2) return -1;if(num1==num2) return 0;if(num1<num2) return 1;
}
ll binarysearch(string n2,ll left,ll right,ll num1){ll mid;while(left<=right){mid=(left+right)/2;int flag=cmp(n2,mid,num1);if(flag==1) right=mid-1;else if(flag==-1) left=mid+1;else return mid;}return -1;
}
int main(){int tag;ll radix;string n1,n2;cin >> n1 >>n2 >> tag >> radix;if(tag!=1){string temp=n1;n1=n2;n2=temp;}ll num1=0,num2=0;num1=converttoten(n1,radix);ll low=1;for(int i=0;i<n2.size();i++){if(chartoint(n2[i])>low) low=chartoint(n2[i]);}low++;ll upper=max(low,num1)+1;ll res=binarysearch(n2,low,upper,num1);if(res==-1) printf("Impossible\n");else printf("%lld\n",res);return 0;}
这道题很有难度,建议参考《算法笔记》。