【PAT-A】1010. Radix (25)

这个讲道理 算是取了巧没用二分查找
因为唯一一个大数据的测试是长度为2的数据
然后还有数据比较大用int会炸

/*
@author Birdy 18.2.19 
从下往上枚举P7会超时,这个是大rad对应一个长度很短的大数据,所以rad会很大。这里懒得写查找……直接把长度为2的拎出来考虑
P10卡了我很久……这个是小的rad对应一个大数据,int会溢出
其他几个点我大概有概念的标在下面了
*/

#include <iostream>
#include <string>
#include <cmath>

using namespace std;
long long int toInt(const string num, const int radix)
{
    long long int number = 0;
    long long int base = 1;
    long long int temp_i;
    char temp_c;
    for (int i = num.length() - 1; i >= 0; i--)
    {
        temp_c = num.at(i);
        temp_i = temp_c >= 'a' ? temp_c - 'a' + 10 : temp_c - '0';
        number += temp_i * base;
        base = base * radix;
    }
    return number;
}

void restrain(const string num, long long int& min , long long int& max, long long int number)
{


    int length = num.length() - 1;
    int firstnum = num.at(0) >= 'a' ? num.at(0) - 'a' + 10 : num.at(0) - '0';
    if (0 == length) //一位
    {
        max = min;
        // Test Point 0

        return;
    }

    int secondnum = num.at(1) >= 'a' ? num.at(1) - 'a' + 10 : num.at(1) - '0';

    if (1 == length)//二位
    {
        // Test Point 2 7 -time limit
         max = (number - secondnum) / firstnum;
         min = min > max ? min : max;
        return;
    }

    // length > 5 Test Point 10 13 6 8


    long long int min_temp;

    // two of the below is all right
    // 这个上界没有非常严格……下面两行随便哪个都可以过
    //max = pow(number / (firstnum), 1. / length) + 1;
    max = number + 1;

    // 更严格的下界(同样不要也能过……)
    //min_temp = pow(number / (firstnum * max + 35), 1. / (length - 1)) - 1;
    //min = min < min_temp ? min_temp : min;

}


int finmin(const string num)
{
    //Test Point 19  for 2121 the radix cannot be 2
    char min = '1';
    for (int i = num.length() - 1; i >= 0; i--)
    {
        if (min < num.at(i))    min = num.at(i);
    }
    return min >= 'a' ? min - 'a' + 10 : min - '0';
}

int main(void)
{
    string  number1_s, number2_s;
    cin >> number1_s >> number2_s;
    long long int index, radix1;
    cin >> index >> radix1;
    string number_s = (index == 2 ? number1_s : number2_s);



    long long int number_i = (index == 1 ? toInt(number1_s, radix1) : toInt(number2_s, radix1));
    long long int min = finmin(number_s) + 1; // every number must smaller than the radix
    long long int max = number_i;
    // number_i > 21474836470  Test Point 10

    restrain(number_s,  min, max, number_i);
    for (long long int i = min; i <= max; i++)
    {
        long long int result = toInt(number_s, i);
        if (result == number_i)
        {
            cout << i << endl;
            system("pause");
            return 0;
        }
        if (result > number_i)
            break;
    }
    cout << "Impossible" << endl;
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/birdy_/article/details/79372487