由于最大乘积问题需要乘积最大的两个数之间的乘积,因此在解决问题时需要考虑整型溢出问题。一种解决方法是使用长整型或高精度计算库来避免溢出。以下是使用 long long 类型和高精度库两种解决方法的示例代码。
使用 long long 类型:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
long long MaxPairwiseProduct(const vector<long long>& numbers) {
int n = numbers.size();
int max_index1 = -1;
for (int i = 0; i < n; ++i)
if ((max_index1 == -1) || (numbers[i] > numbers[max_index1]))
max_index1 = i;
int max_index2 = -1;
for (int j = 0; j < n; ++j)
if ((j != max_index1) && ((max_index2 == -1) || (numbers[j] > numbers[max_index2])))
max_index2 = j;
return numbers[max_index1] * numbers[max_index2];
}
int main() {
int n;
cin >> n;
vector<long long> numbers(n);
for (int i = 0; i < n; ++i) {
cin >> numbers[i];
}
long long result = MaxPairwiseProduct(numbers);
cout << result << endl;
return 0;
}
使用高精度库:
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
class BigInteger {
public:
BigInteger() {
digits.push_back(0);
}
BigInteger(int n) {
while (n > 0) {
digits.push_back(n % 10);
n /= 10;
}
}
BigInteger operator*(const BigInteger& other) const {
BigInteger result;
result.digits.resize(digits.size() + other.digits.size());
for (int i = 0; i < digits.size(); ++i) {
int carry = 0;
for (int j = 0; j < other.digits.size() || carry != 0; ++j) {
int prod = result.digits[i + j] + carry + digits[i] * (j < other.digits.size() ? other.digits[j] : 0);
result.digits[i + j] = prod % 10;
carry = prod / 10;
}
}
while (result.digits.size() > 1 && result.digits.back