Skip to content

Commit 492a9e5

Browse files
committed
Constant optimization
1 parent 4184add commit 492a9e5

File tree

1 file changed

+15
-19
lines changed

1 file changed

+15
-19
lines changed

IZhO/IZhO 19-segments.cpp

+15-19
Original file line numberDiff line numberDiff line change
@@ -7,29 +7,25 @@ IZhO 2019 Bigger Segments
77
- Complexity: O(N)
88
*/
99

10-
#include <bits/stdc++.h>
11-
typedef long long ll;
12-
using namespace std;
10+
#include <stdio.h>
1311

14-
ll a[500001], pref[500001];
15-
pair<int, ll> dp[500001];
12+
long pref[500001], dp_cost[500001];
13+
int dp_cnt[500001], lptr, rptr, dq[500001];
1614

1715
int main() {
18-
ios_base::sync_with_stdio(0);
19-
cin.tie(0);
2016
int n;
21-
cin >> n;
22-
deque<int> dq = {0};
23-
for (int i = 1; i <= n; i++) {
24-
cin >> a[i];
25-
pref[i] = pref[i - 1] + a[i];
26-
while (dq.size() > 1 && pref[i] - pref[dq[1]] >= dp[dq[1]].second)
27-
dq.pop_front();
28-
dp[i] = {dp[dq[0]].first + 1, pref[i] - pref[dq[0]]};
29-
while (dq.size() && dp[dq.back()].second - dp[i].second >= pref[i] - pref[dq.back()])
30-
dq.pop_back();
31-
dq.push_back(i);
17+
scanf("%d", &n);
18+
for (int i = 1; i <= n; ++i) {
19+
scanf("%ld", pref + i);
20+
pref[i] += pref[i - 1];
21+
while (rptr - lptr && pref[i] - pref[dq[lptr + 1]] >= dp_cost[dq[lptr + 1]])
22+
++lptr;
23+
dp_cnt[i] = dp_cnt[dq[lptr]] + 1;
24+
dp_cost[i] = pref[i] - pref[dq[lptr]];
25+
while (dp_cost[dq[rptr]] - dp_cost[i] >= pref[i] - pref[dq[rptr]])
26+
--rptr;
27+
dq[++rptr] = i;
3228
}
33-
cout << dp[n].first;
29+
printf("%d", dp_cnt[n]);
3430
return 0;
3531
}

0 commit comments

Comments
 (0)