码迷,mamicode.com
首页 > 其他好文 > 详细

1010. Radix (25)(进制 + 二分 + 模拟)

时间:2017-05-08 23:29:32      阅读:344      评论:0      收藏:0      [点我收藏+]

标签:ase   for   ecif   char   printf   using   contain   image   output   

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 radixHere 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

 技术分享

Code:

技术分享
 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 typedef unsigned long long LL;
 5 
 6 char a[20], b[20], t[20];
 7 
 8 LL Trans(char s[], int e)
 9 {
10     int len = strlen(s);
11     LL ans = 0;
12     for (int i = 0; i < len; i++)
13     {
14         ans *= e;
15         if (s[i] >= 0 && s[i] <= 9)
16             ans += s[i] - 0;
17         else
18             ans += s[i] - a + 10;
19     }
20     return ans;
21 }
22 
23 int main()
24 {
25     int tag, rad;
26     scanf(" %s %s%d%d" , a , b , &tag , &rad);
27     if (tag == 2)
28     {
29         strcpy(t, a);
30         strcpy(a, b);
31         strcpy(b, t);
32     }
33     LL an = Trans(a, rad);
34     int bmax = 0;
35     int blen = strlen(b);
36     for (int i = 0; i < blen; i++)
37     {
38         if (b[i] >= 0 && b[i] <= 9)
39             bmax = max(bmax, b[i] - 0);
40         else
41             bmax = max(bmax, b[i] - a + 10);
42     }
43 
44     LL l = bmax + 1, r = an;
45     while (l < r)
46     {
47         LL mid = l + r >> 1;
48         LL amid = Trans(b, mid);
49         if (amid == an)
50             l = r = mid;
51         else if (amid < an)
52             l = mid + 1;
53         else
54             r = mid - 1;
55     }
56 
57     if (Trans(b , l) == an)
58         printf("%llu" , l);
59     else
60         printf("Impossible\n");
61     return 0;
62 }
View Code

 

1010. Radix (25)(进制 + 二分 + 模拟)

标签:ase   for   ecif   char   printf   using   contain   image   output   

原文地址:http://www.cnblogs.com/jianglingxin/p/6828025.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!