#include #include #include #include #include using namespace std; vector subsolve(int N, vector A) { A.insert(A.begin(), 0); for (int i = 0; i < N; ++i) { A[i + 1] += A[i]; } // minimize (A[i] - A[j]) + (i - j)^2 = (A[i] + i * i) + (-A[j] + j * j) - 2 * j * i for each i vector intercept(N + 1), slope(N + 1); for (int i = 0; i <= N; ++i) { intercept[i] = -A[i] + 1LL * i * i; slope[i] = -2 * i; } vector seq(N + 1); deque que; for (int i = 0; i <= N; ++i) { if (i >= 1) { seq[i] = que[0]; } while (que.size() >= 2) { int pa = que[que.size() - 2]; int pb = que[que.size() - 1]; double cra = -double(intercept[pa] - intercept[i]) / (slope[pa] - slope[i]); double crb = -double(intercept[pb] - intercept[i]) / (slope[pb] - slope[i]); if (cra > crb) que.pop_back(); else break; } que.push_back(i); while (que.size() >= 2) { int pa = que[0]; int pb = que[1]; long long va = 1LL * slope[pa] * (i + 1) + intercept[pa]; long long vb = 1LL * slope[pb] * (i + 1) + intercept[pb]; if (va > vb) que.pop_front(); else break; } } vector > qs; for (int i = 1; i <= N; ++i) { for (int j = seq[max(i - 5, 0)]; j <= seq[i]; ++j) { if (j != i) { qs.push_back({ A[i] - A[j] + 1LL * (i - j) * (i - j), j, i }); } } } sort(qs.begin(), qs.end()); set st; for (int i = 0; i < N; ++i) { st.insert(i); } vector ans(N); for (vector i : qs) { set::iterator it = st.lower_bound(i[1]); while (it != st.end() && *it < i[2]) { ans[*it] = i[0]; it = st.erase(it); } } return ans; } vector solve(int N, vector A) { vector res1 = subsolve(N, A); reverse(A.begin(), A.end()); vector res2 = subsolve(N, A); reverse(res2.begin(), res2.end()); for (int i = 0; i < N; ++i) { res1[i] = min(res1[i], res2[i]); } return res1; } vector solve_easy(int N, vector A) { vector ans(N, 1LL << 62); for (int i = 0; i < N; ++i) { for (int j = i + 1; j <= N; ++j) { long long sum = 1LL * (j - i) * (j - i); for (int k = i; k < j; ++k) { sum += A[k]; } for (int k = i; k < j; ++k) { ans[k] = min(ans[k], sum); } } } return ans; } #include #include using namespace std; mt19937 mt(1910182301); int rand_rng(int l, int r) { uniform_int_distribution p(l, r - 1); return p(mt); } string stringify(vector A) { string res = "["; for (int i = 0; i < A.size(); ++i) { if (i) res += ", "; res += to_string(A[i]); } res += "]"; return res; } int main() { cin.tie(0); ios_base::sync_with_stdio(false); int N; cin >> N; vector A(N); for (int i = 0; i < N; ++i) cin >> A[i]; vector ans = solve(N, A); for (int i = 0; i < N; ++i) { cout << ans[i] << '\n'; } /* int N = 3; for (int i = 1; i <= 10000; ++i) { vector A(N); for (int j = 0; j < N; ++j) { A[j] = rand_rng(-6, 7); } vector res1 = solve(N, A); vector res2 = solve_easy(N, A); if (res1 != res2) { cout << "Case #" << i << ":" << endl; cout << "N = " << N << ", A = " << stringify(A) << endl; cout << "Returns: " << stringify(res1) << endl; cout << "Answer: " << stringify(res2) << endl; cout << endl; } } */ return 0; }