File tree Expand file tree Collapse file tree
Problems/Data-structures/Day-04/sol Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #include <bits/stdc++.h>
2+ using namespace std;
3+
4+ int main() {
5+ ios::sync_with_stdio(false);
6+ cin.tie(nullptr);
7+
8+ long long x;
9+ int k;
10+ cin >> x >> k;
11+
12+ vector<vector<long long>> lists(k);
13+ for (int i = 0; i < k; i++) {
14+ int l;
15+ cin >> l;
16+ lists[i].resize(l);
17+ for (int j = 0; j < l; j++) {
18+ cin >> lists[i][j];
19+ }
20+ }
21+
22+ // Pointer for each list
23+ vector<int> ptr(k, 0);
24+
25+ // Max heap: {value, list_index}
26+ priority_queue<pair<long long, int>> pq;
27+
28+ // Push first element of each list
29+ for (int i = 0; i < k; i++) {
30+ pq.push({lists[i][0], i});
31+ }
32+
33+ while (!pq.empty()) {
34+ auto [val, idx] = pq.top();
35+ pq.pop();
36+
37+ if (x + val < 0) break;
38+
39+ x += val;
40+ ptr[idx]++;
41+
42+ // Push next element from the same list if exists
43+ if (ptr[idx] < (int)lists[idx].size()) {
44+ pq.push({lists[idx][ptr[idx]], idx});
45+ }
46+ }
47+
48+ cout << x << "\n";
49+ return 0;
50+ }
You can’t perform that action at this time.
0 commit comments