解題思路
若M=∏p[i]^e[i]且總質因數數目t=Σe,排列數是t!/∏e!。同指數型態下,最小M必將較大指數配較小質數,並使用從2開始連續質數。
DFS枚舉非遞增正指數,逐個加入下一質數,最小乘積一超過9999999999就停止。加入e次新質因數時,排列數乘C(t+e,e),因此可精確計算並在已超過N時剪枝。最多33個因數、10種不同質數。
某型態的第二小乘積只可能由最小排列的一次相鄰不同指數交換,或把最後質數換成下一質數得到:任何非最小指派都有一個減小乘積的相鄰交換或質數下移,其前驅若仍非最小就不可能是第二小。收集每型態的最小與這些候選,整體取前兩個不同M相加。質因數乘積採非空,M≥2。
設可行指數型態數P、最多質數種類h≤10,O(P·h)次整數運算、O(P+h)空間;遠小於掃描10^10。 Python一次讀入另佔O(輸入文字長度)空間。
Step-by-step animation
示例:型態(2,1)有3!/2!=3種。
步驟 1 / 3
排列數N=3
型態(2,1)有3!/2!=3種。
2,2,3
2,3,2
3,2,2
- 最小M
- 12
#include <bits/stdc++.h>
using namespace std;
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::cpp_int;
int main() {
cpp_int target;
cin >> target;
const long long LIMIT = 9999999999LL;
vector<int> prime = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}, ex;
set<long long> found;
auto choose = [](int n, int k) {
long long z = 1;
for (int i = 1; i <= k; i++)
z = z * (n - k + i) / i;
return z;
};
function<void(int, int, int, long long, cpp_int)> dfs =
[&](int idx, int prev, int total, long long value, cpp_int ways) {
if (idx && ways == target) {
found.insert(value);
for (int j = 0; j + 1 < idx; j++)
if (ex[j] != ex[j + 1]) {
long long a = value;
for (int t = 0; t < ex[j] - ex[j + 1]; t++)
a = a / prime[j] * prime[j + 1];
if (a <= LIMIT)
found.insert(a);
}
long long a = value;
bool ok = 1;
for (int t = 0; t < ex.back(); t++) {
a /= prime[idx - 1];
if (a > LIMIT / prime[idx]) {
ok = 0;
break;
}
a *= prime[idx];
}
if (ok)
found.insert(a);
}
if (idx >= 10)
return;
long long z = value;
for (int e = 1; e <= prev; e++) {
if (z > LIMIT / prime[idx])
break;
z *= prime[idx];
cpp_int w = ways * choose(total + e, e);
if (w > target)
continue;
ex.push_back(e);
dfs(idx + 1, e, total + e, z, w);
ex.pop_back();
}
};
dfs(0, 33, 0, 1, 1);
auto it = found.begin();
long long a = *it++;
cout << a + *it << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。