洛谷题解P1249 最大乘积
https://www.luogu.com.cn/problem/P1249
本题解基于数学公式推导,并未采取常见的贪心做法。
以下是推导,源论文在最底
(其实就是自己推了大半天发现推出来有些情况没覆盖导致wa了,特意搜了搜,顺便熟悉下latex)
#include <bits/stdc++.h>
using namespace std;struct BigInt {vector<int> d;BigInt(long long x = 0) {if (x == 0) d = { 0 };else while (x > 0) { d.push_back(x % 10); x /= 10; }}string toString() const {if (d.empty()) return "0";string s; s.reserve(d.size());for (auto it = d.rbegin(); it != d.rend(); ++it) s.push_back(char('0' + *it));return s;}void multiply(int x) {if (x == 0) { d = { 0 }; return; }long long carry = 0;for (size_t i = 0; i < d.size(); ++i) {long long t = (long long)d[i] * x + carry;d[i] = int(t % 10);carry = t / 10;}while (carry) {d.push_back(int(carry % 10)); carry /= 10; }}void divide(int x) {if (x == 0) return;long long rem = 0;for (int i = (int)d.size() - 1; i >= 0; --i) {long long cur = rem * 10 + d[i];d[i] = int(cur / x);rem = cur % x;}while (d.size() > 1 && d.back() == 0) d.pop_back();}
};BigInt factorial(int n)
{BigInt r(1);for (int i = 2; i <= n; ++i) r.multiply(i);return r;
}pair<string, vector<int>> maxProductFactors(int n)
{vector<int> factors;if (n == 1) { factors.push_back(1); return { "1", factors }; }double sv = sqrt(8.0 * n + 1);int m = int(floor((sv - 1.0) / 2.0));long long Tm = 1LL * m * (m + 1) / 2;int L = n - (int)Tm;if (L == m) {for (int i = 2; i <= m + 1; ++i) factors.push_back(i);BigInt prod = factorial(m + 1);return { prod.toString(), factors };}if (L == m - 1) {for (int i = 3; i <= m; ++i) factors.push_back(i);factors.push_back(m + 2);BigInt prod = factorial(m);prod.multiply(m + 2);prod.divide(2);return { prod.toString(), factors };}for (int i = 2; i <= m + 1; ++i) if (i != (m - L)) factors.push_back(i);BigInt prod = factorial(m + 1);prod.divide(m - L);return { prod.toString(), factors };
}int main()
{ios::sync_with_stdio(false);cin.tie(nullptr);int n;if (!(cin >> n)) return 0;auto res = maxProductFactors(n);auto& factors = res.second;for (size_t i = 0; i < factors.size(); ++i) {cout << factors[i] << (i + 1 == factors.size() ? '\n' : ' ');}cout << res.first << '\n';return 0;
}
"Maximum Product Over Partitions Into Distinct Parts",
源论文:https://cs.uwaterloo.ca/journals/JIS/VOL8/Doslic/doslic33.pdf