PAT 1010. Radix (25)
2018-01-19 14:26
387 查看
此题高能,甲级里面难度算比较大的了!(其实也不难,关键没指明数据范围)
这题有一个特点:当待处理的字符串只有一位时,答案有多个;当长度大于一位时,只有一个正确答案(或者没有答案)。
如有不当之处欢迎指出!
思路:
最后的答案不止是≤36,也可能特别大(超过int, 达到 long long int)。不能用顺序查找,需用二分查找。这题有一个特点:当待处理的字符串只有一位时,答案有多个;当长度大于一位时,只有一个正确答案(或者没有答案)。
注意
当radix很大的时候,可能会导致计算过程超出long long,需要判断如果是负数,就说明这个radix太大了,应该向更小的查找。AC代码
#define LOCAL #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stack> #include <queue> #include <vector> #include <set> #include <map> #include <string> #include <algorithm> using namespace std; #define INF 0x3f3f3f3f #define Pii pair<int, int> #define MAX_RADIX 1223372036854775807 typedef long long LL; const int MAXN = 10+5; const LL MAX_INTEGER = 9223372036854775807; int get_dig(char ch) { int dig; if(ch >= '0' && ch <= '9') dig = ch - '0'; else dig = ch - 'a' + 10; return dig; } LL get_num(char s[], LL r, LL goal = MAX_INTEGER) { int n = strlen(s); LL res = 0; LL power = r; for(int i = n-1; i >= 0; i--) { int dig = get_dig(s[i]); if(i == n-1) { res = dig; } else { if(r < 0) return -1; //too big res += dig * power; power *= r; } if(res < 0 || res > goal) return -1; //too big } return res; } LL binary_search_radix(char s[], LL goal) { LL low = 0, high = MAX_RADIX; int n = strlen(s); //找到可能的最小radix for(int i = 0; i < n; i++) { low = max(low, (LL)get_dig(s[i])); } low = low + 1; while(low <= high) { LL mid = low + (high - low) / 2; LL res = get_num(s, mid, goal); if(res == goal) return mid; else if(res == -1) high = mid - 1; else low = mid + 1; } return -1; } int main() { #ifdef LOCAL freopen("../DATA/data.in", "r", stdin); freopen("../DATA/data.out", "w", stdout); #endif char a[MAXN], b[MAXN], *c; int tag, radix; while(scanf("%s%s%d%d", a, b, &tag, &radix) == 4) { LL goal; LL r; if(tag == 1) { goal = get_num(a, radix); c = b; } else { goal = get_num(b, radix); c = a; } //特殊处理只有一位的情况 if(strlen(c) == 1) { if(get_dig(c[0]) == goal) r = goal + 1; else r = -1; } else { r = binary_search_radix(c, goal); } if(r == -1) printf("Impossible\n"); else printf("%lld\n", r); } return 0; }
如有不当之处欢迎指出!
相关文章推荐
- ZJU-PAT 1010. Radix (25)
- PAT (Advanced Level) Practise 1010. Radix (25)
- PAT甲题题解-1010. Radix (25)-二分搜索
- PAT 1010. Radix (25)
- PAT-A-1010. Radix (25)
- 【c++】PAT (Advanced Level)1010. Radix (25)
- PAT 1010. Radix (25)
- 【PAT Advanced Level】1010. Radix (25)
- 【PAT甲级】1010. Radix (25)
- PAT甲级 1010.Radix(25) 题目翻译与答案
- [PAT甲级]1010. Radix (25)(求另一个数的基数)
- 1010. Radix (25)-PAT
- PAT习题解:1010. Radix (25)
- PAT (Advanced Level) Practise 1010 Radix (25)
- PAT (Advanced Level) Practise 1010. Radix (25)
- PAT-1010 Radix (25)
- 【PAT-A】1010. Radix (25)
- 【PAT】1010. Radix (25)
- PAT甲级 1010. Radix (25)
- PAT-1010. Radix (25)