(待改进)1010. Radix (25)

来源:互联网 发布:华为mate8root权限软件 编辑:程序博客网 时间:2024/06/05 01:00

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


//基本思路是讲两个数都转为10进制后比较相等与否

//问题在于只知道一个数的进制,另一个未知,我采用的是耿直的暴力枚举

//本题只通过21/25,其他ac了的答主采用的是二分搜索,日后再修改

#include<stdio.h>#include<iostream>#include<string>#include<string.h>using namespace std;#define SIZE 15int todec(char str[], int m){int sum = 0;int lenth = strlen(str);int c = 1;for(int i = lenth-1; i >= 0; i--){int x;if(str[i] >= '0' && str[i] <= '9')x = str[i] - '0';if(str[i] >= 'a' && str[i] <= 'z')x = str[i] - 'a' + 10;if(str[i] == '-')continue;sum += x*c;c *= m;}return sum;}int main(){char str1[SIZE], str2[SIZE];long long int tag, radix;scanf("%s %s %d %d", str1, str2, &tag, &radix);if( (str1[0] == '-' && str2[0] != '-') || (str1[0] != '-' && str2[0] == '-') )cout<<"Impossible";long long int n1 = todec(tag==1? str1:str2, radix);int idx = -1;for(int i = 2; i <= 1000000; i++){long long int n2 = todec(tag==1? str2:str1, i);if(n1 == n2){idx = i;break;}}if( idx != -1){cout<<idx;}elsecout<<"Impossible";return 0;}


原创粉丝点击