美文网首页PTA甲级
题意⚠️整数范围⚠️二分⚠️进制转换 | 1010 Radix

题意⚠️整数范围⚠️二分⚠️进制转换 | 1010 Radix

作者: zilla | 来源:发表于2019-01-23 23:13 被阅读0次

这道 二分+进制转换 写起来不困难,然而竟然是目前看下来通过率最低的一道题(0.11)
坑点不少 ⚠️

  • 题意理解:radix范围( 1 , n1 + 1 ](感谢🙏
  • 数的范围:unsigned long long 刚好可满足。
    图源
    C语言整数类型(含取值范围和长度)
  • 暴力遍历测试点7会TLE,需要二分。

1010 Radix

#include <cstdio>
#include <cstring>
#include <algorithm>

#define N 12
using namespace std;

typedef unsigned long long ULL;

ULL trans2Dec(char digit[], ULL radix) {
    int len = strlen(digit);
    ULL temp = 1, res = 0;
    for (int i = len - 1; i >= 0; --i) {
        if (digit[i] <= '9')
            res += (digit[i] - '0') * temp;
        else res += (digit[i] - 'a' + 10) * temp;
        temp *= radix;
    }
    return res;
}

int main() {
    char num[2][N];
    int tag;
    ULL radix;
    scanf("%s%s%d%llu", num[0], num[1], &tag, &radix);
    tag--;
    //tag
    ULL n1 = trans2Dec(num[tag], radix);
    ULL r2 = 0, r2_low;
    //1-tag
    int index = 1 - tag;
    char mmax = '0';
    int len2 = strlen(num[index]);
    for (int i = 0; i < len2; ++i) {
        mmax = max(mmax, num[index][I]);
    }
    if (mmax >= '0' && mmax <= '9')
        r2_low = mmax - '0' + 1;
    else r2_low = mmax - 'a' + 11;
    /* 测试点7 TLE 考虑二分
    for (int i = r2_low; i <= n1+1; i++) {
        ULL res = trans2Dec(num[index], i);
        if (res == n1) {
            r2 = I;
            break;
        }
        else if (i >= radix && res > n1) {
            r2 = -1;
            break;
        }
    }
     */
    ULL left = r2_low, right = n1 + 1, mid;
    while (left <= right) {
        mid = (left + right) / 2;
        ULL res = trans2Dec(num[index], mid);
        if (res == n1) {
            r2 = mid;
            break;
        } else if (res > n1) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    if (r2 == 0)
        puts("Impossible");
    else printf("%llu\n", r2);
    return 0;
}

相关文章

网友评论

    本文标题:题意⚠️整数范围⚠️二分⚠️进制转换 | 1010 Radix

    本文链接:https://www.haomeiwen.com/subject/silejqtx.html