1010 Radix (25 分)
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
这道题目好像看别人说是有一点问题,我就从中学习吧,也不说这道题目哪里不好。首先,我平时的代码的书写就很乱,平时不喜欢写函数,导致代码量太多,看着很不清晰,要写函数,减少代码量,将代码最清晰的展现出来。
这道题目,一开始就是使用暴力的方法,然后出现超时的样例,最后写了一个二分才AC的,题目挺简单的,只要自信一点就可以过的。
#include<iostream>
#include<bits/stdc++.h>
const int maxn=1005;
using namespace std;
typedef long long ll;
ll strnum(string n,ll rad)
{
ll shu=0;
ll inde=0;
for(auto it=n.rbegin();it!=n.rend();it++)
shu+=(isalpha(*it)?*it-'a'+10:*it-'0')*pow(rad,inde++);
return shu;
}
ll find_rad(ll rad,string yizhi,string buzhi)
{
ll ans=-1;
ll shu=0;
ll index=0;
for(auto it=yizhi.rbegin();it!=yizhi.rend();it++)
shu+=(isalpha(*it)?(*it-'a'+10):(*it-'0') )*pow(rad,index++);
char zimu=*max_element(buzhi.begin(),buzhi.end());
ll left= ( isalpha(zimu)? zimu-'a'+10:zimu-'0') +1;
ll right=max(left,shu);
ll mid;
while(left<=right)
{
mid=(left+right)/2;
ll num=strnum(buzhi,mid);
if(num<0||num>shu)
right=mid-1;
else if(num<shu)
left=mid+1;
else
{
ans=mid;
break;
}
}
return ans;
}
int main()
{
string n1,n2;
ll tag,rad;
cin>>n1>>n2>>tag>>rad;
ll ans= (tag==1? find_rad(rad,n1,n2):find_rad(rad,n2,n1));
if(ans==-1)
cout<<"Impossible"<<endl;
else
cout<<ans<<endl;
return 0;
}
还有一些STL操作使得代码量更小,在一个容器中找到一个最大值,也可以得到他的位置,使得代码量变少。
本文探讨了如何解决1010 Radix问题,通过分析输入的两个正整数,找出使等式成立的进制。文章分享了从暴力解法到二分搜索的优化过程,强调了代码清晰性和效率的重要性。
1089

被折叠的 条评论
为什么被折叠?



