/*
----------------------------------------------------
Author : Johnsondu
Stratege : 水题, 注意要用long long, 没有1进制
10000845 343 What Base Is This? Accepted C++ 0.016 2012-04-17 11:30:42
----------------------------------------------------
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
typedef unsigned long long ll ;
char str1[100], str2[100] ;
int len1, len2 ;
ll tmp1[40], tmp2[40] ;
int res1[40], res2[40] ;
int tmpLen1, tmpLen2 ;
int maxDigit1, maxDigit2 ;
bool flag ;
int ba1, ba2 ;
int max (int a, int b)
{
return a > b ? a : b ;
}
void getMaxDigit () // 找出每个串的最大数,如123,
{ // 那么这个肯定只能从4进制开始
int i, j ;
for (i = 0; i < len1; i ++)
{
if (str1[i] >= '0' && str1[i] <= '9')
maxDigit1 = max(maxDigit1, str1[i] - '0') ;
else if (str1[i] >= 'A' && str1[i] <= 'Z')
maxDigit1 = max (maxDigit1, str1[i] - 'A' + 10) ;
}
for (i = 0; i < len2; i ++)
{
if (str2[i] >= '0' && str2[i] <= '9')
maxDigit2 = max(maxDigit2, str2[i] - '0') ;
else if (str2[i] >= 'A' && str2[i] <= 'Z')
{
maxDigit2 = max (maxDigit2, str2[i] - 'A' + 10) ;
}
}
}
void getValue () // 枚举每个值,保存在数组中
{
int i, j ;
ll tmp ;
tmpLen1 = 0 ;
tmpLen2 = 0 ;
for (i = maxDigit1 + 1; i <= 36; i ++)
{
tmp = 0 ;
for (j = 0; j < len1; j ++)
{
if (str1[j] >= '0' && str1[j] <= '9')
tmp = tmp * i + (str1[j] - '0') ;
else
tmp = tmp * i + (str1[j] - 'A' + 10) ;
}
tmp1[tmpLen1] = tmp ; //保存值
res1[tmpLen1 ++] = i ; //保存进制
}
for (i = maxDigit2 + 1; i <= 36; i ++)
{
tmp = 0 ;
for (j = 0; j < len2; j ++)
{
if (str2[j] >= '0' && str2[j] <= '9')
tmp = tmp * i + (str2[j] - '0') ;
else
tmp = tmp * i + (str2[j] - 'A' + 10) ;
}
tmp2[tmpLen2] = tmp ;
res2[tmpLen2 ++] = i ; //保存进制
}
}
void compare ()
{
int i, j ;
ba1 = 100 ;
ba2 = 0 ;
for (i = 0; i < tmpLen1; i ++)
for (j = 0; j < tmpLen2; j ++)
{
if (tmp1[i] == tmp2[j]) //比较
{
flag = true ;
if (fabs (res1[i] - res2[j]) < fabs (ba1 - ba2)) //找出差值最小的
{
ba1 = res1[i]; //结果1
ba2 = res2[j] ; //结果2
}
}
}
return ;
}
void solve ()
{
maxDigit1 = 0 ;
maxDigit2 = 0 ;
flag = false ;
getMaxDigit () ;
getValue () ;
compare () ;
}
int main ()
{
while (scanf ("%s %s", str1, str2) == 2)
{
len1 = strlen (str1) ;
len2 = strlen (str2) ;
solve () ;
if (flag)
{
if (ba1 == 1)
ba1 ++ ;
if (ba2 == 1)
ba2 ++ ;
printf ("%s (base %d) = %s (base %d)\n", str1, ba1, str2, ba2) ;
}
else
printf ("%s is not equal to %s in any base 2..36\n", str1, str2) ;
}
return 0 ;
}
UVA 343 What Base Is This?
最新推荐文章于 2019-04-06 13:51:12 发布