PAT 1010 Radix (25)

博客围绕1010 Radix问题展开,给定一对正整数N1和N2,需在已知一个数进制的情况下求另一个数的进制。解题采用二分查找,要确定左右界,n2中最大字符对应值+1为下界,上界不超过n1进制,代码中使用unsigned long long类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1010 Radix (25)(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 N​1​​ and 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

Sample Input 3:

12 c 1 10

Sample Output 3:

13

思路:

这真是我做到现在觉得最坑的一题……虽然写了是{0~9,a~z},但是进制远远不止36!因为数字会很大,所以这里用二分查找来做,于是就要确定左右两端的值。n2中最大的字符对应的值+1是查找的下界,需要注意的是如果字符全是‘0’的话下界为2,因为最小是二进制。至于上界的话,n2的进制肯定不会超过n1进制(是n1进制不是n1的进制)。一直用long long也WA了好多遍,最后翻了别人的才知道要unsigned long long。

代码:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cctype>
#include <climits>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>  
#include <set>
using namespace std;

int ctoi[127];

unsigned long long convert(string s, int r)
{
	long long n = 0;
	for (int i = 0; i <s.length(); i++)
		n = n*r+ctoi[(s[i])];
	return n;
}

int find_left(string s)
{
	char max = 0;
	for (int i = 0; i < s.length(); i++)
	{
		if (s[i] > max)
			max = s[i];
	}
	if (max == '0')
		return 2;
	else
		return ctoi[max] + 1;
}

int main()
{
	for (int i = '0'; i <= '9'; i++)
		ctoi[i] = i - '0';
	for (int i = 'a'; i <= 'z'; i++)
		ctoi[i] = i - 'a' + 10;
	string s1, s2;
	int tag, radix;
	unsigned long long n1, n2, l, r, m;
	cin >> s1 >> s2 >> tag >> radix;
	if (tag == 2)
		swap(s1, s2);
	n1 = convert(s1, radix);
	l = find_left(s2);
	r = n1;
	while (l < r)
	{
		m = (l + r) / 2;
		n2 = convert(s2, m);
		if (n2 == n1)
			l = r = m;
		else if (n2 > n1)
			r = m - 1;
		else
			l = m + 1;
	}
	if (convert(s2, l) == n1)
		cout << l << endl;
	else
		cout << "Impossible" << endl;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值