Skip to content

Commit a077fe2

Browse files
authored
Merge pull request #387 from Aaryan-Degama/d4q2
D4q2
2 parents e0071a8 + c471f64 commit a077fe2

1 file changed

Lines changed: 63 additions & 0 deletions

File tree

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// link : https://codeforces.com/problemset/submission/1912/355879512
2+
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
6+
using ll = long long;
7+
using vi = vector<pair<ll, ll>>;
8+
9+
int main() {
10+
ll init_pow, k;
11+
cin >> init_pow >> k;
12+
13+
vi seg;
14+
15+
for (ll grp = 0; grp < k; grp++) {
16+
ll n;
17+
cin >> n;
18+
19+
ll cur = 0, min_pref = 0;
20+
21+
for (ll i = 0; i < n; i++) {
22+
ll x;
23+
cin >> x;
24+
25+
cur += x;
26+
min_pref = max(min_pref, -cur);
27+
28+
if (cur > 0) {
29+
seg.push_back({min_pref, cur});
30+
cur = 0;
31+
}
32+
}
33+
}
34+
35+
sort(seg.begin(), seg.end());
36+
37+
for (auto p : seg) {
38+
if (p.first > init_pow) break;
39+
init_pow += p.second;
40+
}
41+
42+
cout << init_pow << '\n';
43+
return 0;
44+
}
45+
46+
47+
/*
48+
Explanation:
49+
50+
Each group is split into profitable segments. While reading a group, `cur`
51+
stores the running sum and `min_pref` stores the maximum deficit
52+
(-prefix sum), i.e., the minimum power required to start that segment.
53+
Whenever `cur > 0`, the segment is stored as (min_pref, cur) and `cur` is reset.
54+
55+
All segments are sorted by required power and processed greedily.
56+
If the required power of a segment exceeds current power, we stop;
57+
otherwise, we add its gain.
58+
59+
Time Complexity: O(N log N)
60+
Space Complexity: O(N).
61+
62+
63+
*/

0 commit comments

Comments
 (0)