PAT1010 Radix (25 分)

这里写目录标题

1 问题描述

PAT1010 Radix (25 分)

2 思路

不同进制转化成十进制很容易,但是对于另一个难点在于另一个数字进制的寻找,范围应该是进制位置的数的所有数位上数值最大的一个数+1,到N1+1(考虑到N2只有一位的情况),为了降低时间复杂度就要用二分在上述范围内的查找相对应的进制基数。当N2>N1,或者N2<0(N2过大),就在右半区间寻找,否则就在左半区间寻找(N2过小),此外用二分法可以完美满足若右多个进制满足要就输出最小的进制的要求

AC代码

#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
long long getnum(string str, long long radix)
{
	long long sum = 0;
	for (int i = 0; i < str.length(); i++)
	{
		if (str[i] <= '9' && str[i] >= '0')
		{
			sum = sum * radix + (str[i] - '0');
		}
		else if (str[i] <= 'z' && str[i] >= 'a')
		{
			sum = sum * radix + (str[i] - 'a' + 10);
		}

	}
	return sum;
}
int getMinRadix(string num2) {
	char max = '0';
	for (int i = 0; i < num2.length(); ++i)
		if (num2[i] > max)max = num2[i];
	if (max <= '9')return max - '0' + 1;
	else return max - 'a' + 11;
}

long long  binarySearch(string str, long long low, long long high, long long N1)
{
	long long mid = 0;
	while (low <= high)
	{
		mid = (low + high) / 2;
		if (getnum(str, mid) == N1) return mid;
		else if (low == high && getnum(str, low) != N1) break;
		else if (getnum(str, mid) > N1 || getnum(str, mid) < 0) high = mid;
		else low = mid + 1;
	}

	return 0;
}

int main()
{
	string num1, num2;
	int tag, radix, N1, N2, i, j;
	long long res,high;
	cin >> num1 >> num2 >> tag >> radix;
    if (num1 == num2) {
		cout << radix << endl;
		return 0;
	}
	if (tag == 2)
	{
		N1 = getnum(num2, radix);
		num2 = num1;
	}
	else {
		N1 = getnum(num1, radix);
	}
	high = max(getMinRadix(num2), N1);
	res = binarySearch(num2, getMinRadix(num2), high, N1);
	if (res==0)
	{
		cout << "Impossible" << endl;
	}
	else
	{
		cout << res << endl;
	}


	return 0;
}

心得体会

二分查找可以有效减小查找的时间复杂度。

三级目录

上一篇:2021-07-26


下一篇:Django(8)reverse函数