1010 Radix (manejo de desbordamiento, dicotomía)

#include<cstdio>
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
typedef long long LL;
int toInt(char c)
{
	if(c>='0'&&c<='9') return c-'0';
	else return c-'a'+10;
}
LL toDecNorm(string s, int radix)//把s1变为10进制 
{
	LL ans=0;
	for(int i=0; i<s.size(); i++){
		ans = ans*radix+toInt(s[i]);
	}
	return ans;
}
LL toDecSpec(string s, LL radix, LL sup)
{
	/*如果变成负数就说明溢出,溢出就说明肯定大于
	n1,如果在转化过程中大于sup,那么也可以及时
	终止程序并且返回-1*/ 
	LL ans=0;
	for(int i=0; i<s.size(); i++){
		ans = ans*radix+toInt(s[i]);
		if(ans<0||ans>sup) return -1;
	}
	return ans;//返回的ans小于等于sup 
}
LL binarySearch(LL n1, string s2, LL left, LL right)
{
	LL mid,n2;
	while(left<=right){
		mid = (left+right)/2;
		n2 = toDecSpec(s2,mid,n1);
		if(n2<0) right = mid-1;
		else if(n1>n2) left = mid+1;
		else if(n1<n2) right = mid-1;
		else return mid;
	}
	return -1;
}
int main()
{
	string s1,s2;
	int tag,radix;
	cin>>s1>>s2>>tag>>radix;
	if(tag==2){
		string tmp = s1;
		s1 = s2;
		s2 = tmp;
	}
	//已知进制数的最大值不会超过long long
	LL n1 = toDecNorm(s1,radix); 
	//找到搜索的下界和上界 
	LL low=-1, high;
	for(int i=0; i<s2.size(); i++){
		if(toInt(s2[i])>low) low = toInt(s2[i]);
	}
	low++;
    low = max(low,2ll);//low要大于2,这句其实多余
	high = max(low, n1+1);
	LL ans = binarySearch(n1,s2,low,high);
	if(ans==-1) printf("Impossible\n");
	else printf("%lld\n",ans);
	return 0;
}







 

Supongo que te gusta

Origin blog.csdn.net/yiwaite/article/details/112802268
Recomendado
Clasificación