Advertisement
tuki2501

atcoder_dp_z.cpp

Nov 10th, 2021
1,198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef long long ll;
  5.  
  6. const int N = 200005;
  7. const ll INF = 1e18;
  8.  
  9. struct Line {
  10.   ll a, b;
  11.   Line() { a = 0; b = INF; }
  12.   Line(ll a, ll b): a(a), b(b) {}
  13.   ll operator()(ll x) { return a * x + b; }
  14. };
  15.  
  16. struct Node {
  17.   Line line;
  18.   Node *lef, *rig;
  19.   Node() { lef = rig = nullptr; }
  20. };
  21.  
  22. struct LCT {
  23.   Node *node;
  24.   LCT() { node = new Node; }
  25.   void insert(Node *&node, ll l, ll r, Line line) {
  26.     if (l > r) return;
  27.     if (node == nullptr) node = new Node;
  28.     if (l == r) {
  29.       if (line(l) < node->line(l)) node->line = line;
  30.       return;
  31.     }
  32.     ll m = (l + r) / 2;
  33.     if (line.a > node->line.a) swap(line, node->line);
  34.     if (line(m) < node->line(m)) {
  35.       swap(line, node->line);
  36.       insert(node->lef, l, m, line);
  37.     }
  38.     else insert(node->rig, m + 1, r, line);
  39.   }
  40.   ll get(Node *&node, ll l, ll r, ll x) {
  41.     if (l > r || node == nullptr) return INF;
  42.     if (l == r) return node->line(x);
  43.     ll m = (l + r) / 2;
  44.     if (x < m) return min(node->line(x), get(node->lef, l, m, x));
  45.     else return min(node->line(x), get(node->rig, m + 1, r, x));
  46.   }
  47.   void insert(Line line) {
  48.     insert(node, 1, 1e6, line);
  49.   }
  50.   ll get(ll x) {
  51.     return get(node, 1, 1e6, x);
  52.   }
  53. };
  54.  
  55. ll sqr(ll x) {
  56.   return x * x;
  57. }
  58.  
  59. int n;
  60. ll c, h[N], dp[N];
  61.  
  62. int main() {
  63.   cin.tie(0)->sync_with_stdio(0);
  64.   cin >> n >> c;
  65.   for (int i = 1; i <= n; i++) {
  66.     cin >> h[i];
  67.   }
  68.   LCT lct;
  69.   for (int i = 1; i <= n; i++) {
  70.     if (i == 1) dp[i] = 0;
  71.     else dp[i] = lct.get(h[i]) + sqr(h[i]) + c;
  72.     lct.insert(Line(-2 * h[i], dp[i] + sqr(h[i])));
  73.   }
  74.   cout << dp[n] << '\n';
  75. }
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement