公式
B - Break a Stick 解説 by en_translator
When the stick is broken at the \(i\)-th notch, the two sticks have lengths \(L_1+L_2+\cdots+L_i\) and \(L_{i+1}+L_{i+2}+\cdots+L_N\).
Compute these lengths and their absolute difference for all notch, and print the minimum value among them.
(This time, the constraints allows to add up one by one, but using cumulative sums or differential updates makes it faster.)
Sample code (C++)
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin >> N;
vector<int> L(N);
for (int &l : L) cin >> l;
int ans = 1000000000;
for (int i = 1; i < N; i++) {
int sum_l = 0, sum_r = 0;
for (int j = 0; j < i; j++) sum_l += L[j];
for (int j = i; j < N; j++) sum_r += L[j];
ans = min(ans, abs(sum_l - sum_r));
}
cout << ans << endl;
}
Sample code (Python)
N = int(input())
L = list(map(int, input().split()))
ans = min(abs(sum(L[:i]) - sum(L[i:])) for i in range(1, N))
print(ans)
投稿日時:
最終更新: