P1001 a+b problem 题解

· · 学习·文化课

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <stdexcept>
#include <complex>
#include <cmath>

using namespace std;

using cd = complex<double>;
const double PI = acos(-1);

// FFT核心函数:将多项式从系数空间转换到点值空间
void fft(vector<cd>& a, bool invert) {
    int n = a.size();
    if (n <= 1) return;

    vector<cd> a0(n / 2), a1(n / 2);
    for (int i = 0; 2 * i < n; ++i) {
        a0[i] = a[2*i];
        a1[i] = a[2*i + 1];
    }
    fft(a0, invert);
    fft(a1, invert);

    double ang = 2 * PI / n * (invert ? -1 : 1);
    cd w(1), wn(cos(ang), sin(ang));
    for (int i = 0; 2 * i < n; ++i) {
        a[i] = a0[i] + w * a1[i];
        a[i + n/2] = a0[i] - w * a1[i];
        if (invert) {
            a[i] /= 2;
            a[i + n/2] /= 2;
        }
        w *= wn;
    }
}

// 基于FFT的多项式乘法(返回卷积结果)
vector<long long> multiply_fft(const vector<int>& a, const vector<int>& b) {
    vector<cd> fa(a.begin(), a.end()), fb(b.begin(), b.end());
    int n = 1;
    while (n < (int)(a.size() + b.size())) 
        n <<= 1; // 取最小的2的幂作为FFT长度
    fa.resize(n);
    fb.resize(n);

    fft(fa, false);
    fft(fb, false);
    for (int i = 0; i < n; ++i)
        fa[i] *= fb[i];
    fft(fa, true); // 逆FFT转换回系数

    vector<long long> result(n);
    for (int i = 0; i < n; ++i)
        result[i] = round(fa[i].real()); // 取实部并四舍五入
    return result;
}

class BigInt {
private:
    int sign; // 1: 正数, -1: 负数, 0: 零
    vector<int> digits; // 存储数字,从低位到高位

    // 移除前导零
    void removeLeadingZeros() {
        while (!digits.empty() && digits.back() == 0) {
            digits.pop_back();
        }
        if (digits.empty()) {
            sign = 0;
        }
    }

public:
    // 新增:获取digits的公共接口(解决私有成员访问问题)
    const vector<int>& getDigits() const {
        return digits;
    }

    // 构造函数
    BigInt() : sign(0) {}
    BigInt(const string& s) {
        if (s.empty()) {
            sign = 0;
            return;
        }
        int start = 0;
        if (s[0] == '-') {
            sign = -1;
            start = 1;
        } else {
            sign = 1;
        }
        // 从字符串尾部(高位)向头部(低位)读取,存储为低位到高位
        for (int i = s.size() - 1; i >= start; --i) {
            digits.push_back(s[i] - '0');
        }
        removeLeadingZeros();
    }
    BigInt(long long n) : BigInt(to_string(n)) {}

    // 辅助函数
    bool isZero() const { return sign == 0; }
    int getSign() const { return sign; }
    BigInt abs() const {
        BigInt res = *this;
        res.sign = res.isZero() ? 0 : 1;
        return res;
    }

    // 加法运算
    BigInt operator+(const BigInt& other) const {
        if (sign == 0) return other;
        if (other.sign == 0) return *this;
        if (sign != other.sign) { // 异号,转化为减法
            BigInt temp = other;
            temp.sign *= -1;
            return *this - temp;
        }
        // 同号,直接相加
        BigInt res;
        res.sign = sign;
        int carry = 0;
        size_t i = 0;
        while (i < digits.size() || i < other.digits.size() || carry) {
            int sum = carry;
            if (i < digits.size()) sum += digits[i];
            if (i < other.digits.size()) sum += other.digits[i];
            carry = sum / 10;
            res.digits.push_back(sum % 10);
            ++i;
        }
        res.removeLeadingZeros();
        return res;
    }

    // 减法运算
    BigInt operator-(const BigInt& other) const {
        if (sign == 0) { // 被减数为零,结果为减数的相反数
            BigInt res = other;
            res.sign *= -1;
            return res;
        }
        if (other.sign == 0) return *this; // 减数为零,结果为被减数
        if (sign != other.sign) { // 异号,转化为加法
            BigInt temp = other;
            temp.sign *= -1;
            return *this + temp;
        }
        // 同号,比较绝对值后相减
        BigInt a_abs = abs();
        BigInt b_abs = other.abs();
        if (a_abs < b_abs) { // 被减数绝对值小,结果为负
            BigInt res = b_abs - a_abs;
            res.sign *= -1;
            return res;
        }
        // 被减数绝对值大,直接相减
        BigInt res;
        res.sign = sign;
        int borrow = 0;
        size_t i = 0;
        while (i < a_abs.digits.size() || i < b_abs.digits.size()) {
            int digitA = borrow;
            if (i < a_abs.digits.size()) digitA += a_abs.digits[i];
            if (i < b_abs.digits.size()) digitA -= b_abs.digits[i];
            if (digitA < 0) { // 需要借位
                digitA += 10;
                borrow = -1;
            } else {
                borrow = 0;
            }
            res.digits.push_back(digitA);
            ++i;
        }
        res.removeLeadingZeros();
        return res;
    }

    // 乘法运算(基于FFT实现,修正私有成员访问)
    BigInt operator*(const BigInt& other) const {
        if (isZero() || other.isZero()) return BigInt("0");

        // 符号单独处理(同号为正,异号为负)
        BigInt res;
        res.sign = sign * other.sign;

        // 修正:通过公共接口获取digits(原代码直接访问私有成员导致编译错误)
        vector<int> a_digits = this->abs().getDigits();
        vector<int> b_digits = other.abs().getDigits();

        // FFT计算卷积(得到未处理进位的乘积)
        vector<long long> conv = multiply_fft(a_digits, b_digits);

        // 处理进位(将卷积结果转换为10进制 digits)
        long long carry = 0;
        for (size_t i = 0; i < conv.size() || carry; ++i) {
            long long sum = carry;
            if (i < conv.size()) sum += conv[i];
            res.digits.push_back(sum % 10); // 当前位
            carry = sum / 10; // 进位到下一位
        }

        res.removeLeadingZeros();
        return res;
    }

    // 乘以小整数
    BigInt multiplyByInt(int n) const {
        if (n == 0) return BigInt("0");
        BigInt res = *this;
        int carry = 0;
        size_t i = 0;
        while (i < res.digits.size() || carry) {
            long long product = carry;
            if (i < res.digits.size()) {
                product += (long long)res.digits[i] * n;
            }
            carry = product / 10;
            if (i < res.digits.size()) {
                res.digits[i] = product % 10;
            } else {
                res.digits.push_back(product % 10);
            }
            ++i;
        }
        res.removeLeadingZeros();
        return res;
    }

    // 除以小整数
    BigInt divideByInt(int n) const {
    if (n == 0) throw runtime_error("除数不能为零");
    BigInt res;
    res.sign = sign * (n > 0 ? 1 : -1); // 符号由被除数和除数符号决定
    n = std::abs(n); // 修正:明确调用全局abs处理int类型
    int remainder = 0;
    // 从高位到低位计算商
    for (int i = (int)digits.size() - 1; i >= 0; --i) {
        remainder = remainder * 10 + digits[i];
        int q = remainder / n;
        remainder %= n;
        res.digits.push_back(q);
    }
    reverse(res.digits.begin(), res.digits.end()); // 调整为低位在前
    res.removeLeadingZeros();
    if (remainder != 0) {
        throw runtime_error("除法结果不是整数(不符合预期)");
    }
    return res;
}
    // 开平方
    BigInt sqrt() const {
        if (sign < 0) throw runtime_error("不能对负数开平方");
        if (isZero()) return BigInt("0");
        // 二分法查找平方根
        BigInt low("0");
        BigInt high = *this;
        BigInt mid;
        while (low <= high) {
            mid = (low + high).divideByInt(2); // 取中间值
            BigInt mid_sq = mid * mid; // 此处乘法已用FFT
            if (mid_sq == *this) {
                return mid;
            } else if (mid_sq < *this) {
                low = mid + BigInt("1");
            } else {
                high = mid - BigInt("1");
            }
        }
        throw runtime_error("输入不是完全平方数(不符合预期)");
    }

    // 比较运算符
    bool operator==(const BigInt& other) const {
        if (sign != other.sign) return false;
        if (digits.size() != other.digits.size()) return false;
        for (size_t i = 0; i < digits.size(); ++i) {
            if (digits[i] != other.digits[i]) return false;
        }
        return true;
    }

    bool operator<(const BigInt& other) const {
        if (sign != other.sign) {
            return sign < other.sign; // 负数小于正数
        }
        if (sign == 1) { // 都是正数,比较绝对值
            if (digits.size() != other.digits.size()) {
                return digits.size() < other.digits.size();
            }
            for (int i = (int)digits.size() - 1; i >= 0; --i) {
                if (digits[i] != other.digits[i]) {
                    return digits[i] < other.digits[i];
                }
            }
            return false; // 相等
        } else { // 都是负数,绝对值大的反而小
            if (digits.size() != other.digits.size()) {
                return digits.size() > other.digits.size();
            }
            for (int i = (int)digits.size() - 1; i >= 0; --i) {
                if (digits[i] != other.digits[i]) {
                    return digits[i] > other.digits[i];
                }
            }
            return false; // 相等
        }
    }

    bool operator<=(const BigInt& other) const {
        return *this < other || *this == other;
    }

    // 转换为字符串(用于输出)
    string toString() const {
        if (isZero()) return "0";
        string s;
        if (sign == -1) s += "-";
        // 从高位到低位输出
        for (auto it = digits.rbegin(); it != digits.rend(); ++it) {
            s += char('0' + *it);
        }
        return s;
    }
};

int main() {
    string a_str, b_str;
    cin >> a_str >> b_str;
    BigInt a(a_str);
    BigInt b(b_str);

    // 步骤1:计算t = a*b(所有乘法均用FFT实现)
    BigInt s = a + b;                     // s = a + b
    BigInt d = a - b;                     // d = a - b
    BigInt s_sq = s * s;                  // s2(FFT乘法)
    BigInt d_sq = d * d;                  // d2(FFT乘法)
    BigInt diff = s_sq - d_sq;            // s2 - d2
    BigInt diff_sq = diff * diff;         // (s2 - d2)2(FFT乘法)
    BigInt sqrt_diff_sq_abs = diff_sq.sqrt(); // sqrt依赖FFT乘法
    BigInt sqrt_diff_sq = sqrt_diff_sq_abs.multiplyByInt(diff.getSign()); 
    BigInt t = sqrt_diff_sq.divideByInt(4); // t = diff / 4 = a*b

    // 步骤2:计算sqrt(a2 + 2t + b2)(乘法用FFT)
    BigInt a_sq = a * a;                  // a2(FFT乘法)
    BigInt two_t = t.multiplyByInt(2);    // 2t
    BigInt b_sq = b * b;                  // b2(FFT乘法)
    BigInt sum = a_sq + two_t + b_sq;     // a2 + 2t + b2
    BigInt result = sum.sqrt();           // 开平方依赖FFT乘法

    cout << result.toString() << endl;    // 输入20和30时,输出应为50

    return 0;
}

一、题目分析:明确核心要求

本题的核心需求可概括为两点:

  1. 用东风6c打击蚊子:必须通过 sqrt([(a+b)2-(a-b)2]2)/4 计算 t = a*b,再通过 sqrt(a2 + 2t + b2) 计算最终结果,即使代数上可化简(如 (a+b)2 = a2 + 2ab + b2),也必须按原始步骤执行。
  2. 高精度+FFT实现:由于 a, b 范围接近 INT_MAX(约±2×10?),其平方、乘积等中间结果可能远超普通整数类型的表示范围,需用高精度整数(BigInt)存储;且所有乘法必须用FFT(快速傅里叶变换)优化,以提升大整数乘法效率。

二、解题思路:拆解计算步骤

按题目要求,整体流程分为两大步,每一步需严格遵循“不化简”原则,且依赖高精度运算和FFT乘法:

步骤1:计算 t = a*b(通过指定公式)

需执行以下子步骤(每步均为高精度运算,乘法用FFT):

步骤2:计算最终结果 sqrt(a2 + 2t + b2)

需执行以下子步骤(乘法用FFT):

三、测试验证:以输入 20 和 30 为例

通过具体案例验证步骤正确性:

四、吐槽与总结

本题涉及到高精度混合运算(含开根)与快速傅里叶变换(FFT),综合难度为省选/NOI-,为什么是红题!