File tree 2 files changed +81
-3
lines changed
2 files changed +81
-3
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * slope trick!
3
+ *
4
+ * https://usaco.guide/adv/slope
5
+ */
6
+
7
+ #include < bits/stdc++.h>
8
+
9
+ using namespace std ;
10
+
11
+ using ll = long long ;
12
+ #define ii pair<int , int >
13
+ #define f first
14
+ #define s second
15
+ #define pb push_back
16
+ #define mp make_pair
17
+ #define all (x ) x.begin(), x.end()
18
+ #define sz (x ) (int )x.size()
19
+ #define F0R (i, n ) for (int i = 0 ; i < n; i++)
20
+ #define FOR (i, a, b ) for (int i = a; i < b; i++)
21
+ #define inf 1000000010
22
+
23
+ int main () {
24
+ cin.tie (0 )->sync_with_stdio (0 );
25
+
26
+ int n; cin >> n;
27
+
28
+ ll dp0 = 0 ; // y-intercept
29
+
30
+ // slope increases by one at each of these points
31
+ priority_queue<ll> slopeChanges;
32
+
33
+ ll initialSlope = 0 ;
34
+
35
+ ll totA = 0 , totB = 0 ;
36
+ ll diff;
37
+ F0R (i, n) {
38
+ int a, b; cin >> a >> b; totA += a; totB += b;
39
+
40
+ diff = totA - totB;
41
+
42
+ dp0 += abs (diff);
43
+ initialSlope--;
44
+
45
+ // at x = diff, the function slope changes by two
46
+ slopeChanges.push (diff);
47
+ slopeChanges.push (diff);
48
+
49
+ // remove the final slope change that will cause the slope to become positive
50
+ slopeChanges.pop ();
51
+ }
52
+
53
+ // Want to calculate dp value where x = diff (the final difference)
54
+ vector<ll> changes;
55
+ while (!slopeChanges.empty ()) { changes.pb (slopeChanges.top ()); slopeChanges.pop (); }
56
+ reverse (all (changes));
57
+ ll curX = 0 , slope = initialSlope;
58
+ for (ll x : changes) {
59
+ ll dist = x - curX;
60
+ if (x >= diff) {
61
+ dp0 += slope*dist;
62
+ break ;
63
+ }
64
+ if (x >= 0 ) {
65
+ dp0 += slope*dist;
66
+ curX = x;
67
+ }
68
+ slope++;
69
+ }
70
+
71
+ cout << dp0 << endl;
72
+
73
+ return 0 ;
74
+ }
Original file line number Diff line number Diff line change 1
- 20
2
- 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4
3
-
1
+ 6
2
+ 1 2
3
+ 0 0
4
+ 2 0
5
+ 0 0
6
+ 0 0
7
+ 0 1
You can’t perform that action at this time.
0 commit comments