NonSequitur

Untitled

May 20th, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define ll long long
  3.  
  4. using namespace std;
  5.  
  6. const int N = 50050;
  7.  
  8. struct node {
  9.     ll best, max, min;
  10.     bool valid;
  11.  
  12.     node() : valid(false) { }
  13.  
  14.     node(ll value, ll sum) {
  15.         best = value;
  16.         min = sum - value;
  17.         max = sum;
  18.         valid = true;
  19.     }
  20. };
  21.  
  22. template<typename Node>
  23. node join(Node&& left, Node&& right) {
  24.     node ret;
  25.     ret.valid = true;
  26.     ret.best = max(max(left.best, right.best), right.max - left.min);
  27.     ret.max = max(left.max, right.max);
  28.     ret.min = min(left.min, right.min);
  29.     return ret;
  30. }
  31.  
  32. node t[4 * N];
  33. int values[N];
  34. ll sum[N];
  35.  
  36. void build(int i, int l, int r) {
  37.     if (l == r) t[i] = node(values[l], sum[l]);
  38.     else {
  39.         build(i * 2, l, (l + r) / 2);
  40.         build(i * 2 + 1, (l + r) / 2 + 1, r);
  41.         t[i] = join(t[i * 2], t[i * 2 + 1]);
  42.     }
  43. }
  44.  
  45. node query(int i, int l, int r, int a, int b) {
  46.     if (r < a || l > b) return node();
  47.     else if (a <= l && b >= r) return t[i];
  48.  
  49.     auto left = query(i * 2, l, (l + r) / 2, a, b);
  50.     auto right = query(i * 2 + 1, (l + r) / 2 + 1, r, a, b);
  51.  
  52.     if (!left.valid) return right;
  53.     else if (!right.valid) return left;
  54.  
  55.     return join(left, right);
  56. }
  57.  
  58. int main() {
  59.     int n;
  60.     scanf("%d", &n);
  61.  
  62.     for (int i = 1; i <= n; i++) {
  63.         scanf("%d", values + i);
  64.         sum[i] += sum[i - 1] + values[i];
  65.     }
  66.  
  67.     build(1, 1, n);
  68.  
  69.     int m;
  70.     scanf("%d", &m);
  71.  
  72.     int l, r;
  73.     while (m--) {
  74.         scanf("%d%d", &l, &r);
  75.         printf("%lld\n", query(1, 1, n, l, r).best);
  76.     }
  77.  
  78.     return 0;
  79. }
Add Comment
Please, Sign In to add comment