算法1
第一列纯1,特判1即可
第二列d=1等差数列,行数是n+1
第三列等差数列的和,不偷懒了,上个二分查找
其后第四列起均为C(3+,n),行数很少,枚举即可
时间复杂度
二分等差数列和 O(loglogn)
参考文献
C++ 代码
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
ll qs(ll n) {
if (n < 2)return INT_MAX;
return n * (n + 1) / 2;
}
ll com(ll u, ll d) {
if (u > d)return -1ll;
ll ans = 1;
for (ll i = 1; i <= u; i++) {
ans *= d - i + 1;
ans /= i;
}
return ans;
}
ll cq(ll a, ll b) {
return qs(a) + b;
}
int main() {
ll n;
cin >> n;
ll ans = cq(n, 2);
if (n == 1) {
cout << 1;
return 0;
}
ll l = 4, r = INT_MAX;
while (l < r) {
ll m = (l + r) / 2;
ll t = qs(m - 1);
if (t < n) {
l = m + 1;
}
else if (t > n) {
r = m - 1;
}
else {
ans = min(ans, cq(m, 3));
break;
}
}
for (ll u = 4; u < 1e3; u++) {
for (ll d = u * 2; 1; d++){
ll t = com(u - 1, d);
if (t > n)break;
if (t == n) {
ans = min(ans, cq(d, u));
break;
}
}
}
cout << ans;
return 0;
}