PAT 1010. Radix (25)

http://www.patest.cn/contests/pat-a-practise/1010

以为要写大数呢,改成 long long 就过了, 嚓

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 
 4 #define MAX(A, B) ((A) > (B) ? (A) : (B))
 5 
 6 long long least_radix(char *s) {
 7     long long result = 0;
 8     while(*s) {
 9         if (*s >= '0' && *s <= '9') {
10             result = MAX(result, *s - '0');
11         } else if (*s >= 'a' && *s <= 'z') {
12             result = MAX(result, *s - 'a' + 10);
13         }
14         ++s;
15     }
16     return result + 1;
17 }
18 
19 long long to_dicimal(char *s, long long radix) {
20     long long result = 0;
21     while(*s) {
22         if (*s >= '0' && *s <= '9') {
23             result = result * radix + *s - '0';
24         } else if (*s >= 'a' && *s <= 'z') {
25             result = result * radix + *s - 'a' + 10;
26         }
27         ++s;
28     }
29     return result;
30 }
31 
32 long long getupper(long long dicimal_num, char *s, long long radix) {
33     while(1) {
34         long long num = to_dicimal(s, radix);
35         if (num < dicimal_num) radix *= 2;
36         else break;
37     }
38     return radix;
39 }
40 
41 long long mybsearch(long long dicimal_num, char *s, long long radix) {
42     long long radix_l = radix;
43     long long radix_h = getupper(dicimal_num, s, radix);
44     while(radix_l <= radix_h) {
45         long long mid = radix_l + ((radix_h - radix_l) >> 1);
46         long long num = to_dicimal(s, mid);
47         if (num == dicimal_num) {
48             return mid;
49         } else if (num < dicimal_num) {
50             radix_l = mid + 1;
51         } else {
52             radix_h = mid -1;
53         }
54     }
55     return -1;
56 }
57 
58 
59 int main() {
60     char n1[100], n2[100];
61     long long tag, radix;
62     scanf("%s %s %lld %lld", n1, n2, &tag, &radix);
63     long long dicimal_num = 0;
64     long long result_radix = 0;
65     if (tag == 1) {
66         dicimal_num = to_dicimal(n1, radix);
67         result_radix = mybsearch(dicimal_num, n2, least_radix(n2));
68     } else {
69         dicimal_num = to_dicimal(n2, radix);
70         result_radix = mybsearch(dicimal_num, n1, least_radix(n1));
71     }
72     if (result_radix < 0) {
73         printf("Impossible\n");
74     } else printf("%lld\n", result_radix);
75     return 0;
76 }

 

posted @ 2015-07-29 15:16  ACSeed  Views(245)  Comments(0)    收藏  举报