Advertisement
Guest User

Untitled

a guest
Oct 14th, 2016
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdio.h>
  3.  
  4. using namespace std;
  5. typedef long long ll;
  6.  
  7. struct Node {
  8. ll left;
  9. ll right;
  10. ll sum;
  11. ll best;
  12. };
  13.  
  14. int a[100000];
  15. Node tree[1000000];
  16.  
  17. int max(int n1, int n2)
  18. {
  19. if (n1 > n2)return n1;
  20. return n2;
  21. }
  22.  
  23.  
  24. void build_tree(int node, int start, int endd)
  25. {
  26. if (start == endd) {
  27. tree[node].right = tree[node].left = tree[node].best = tree[node].sum = a[start];
  28. return;
  29. }
  30. int mid = (start + endd) / 2;
  31. build_tree(node * 2, start, mid);
  32. build_tree((node * 2) + 1, mid + 1, endd);
  33. tree[node].left = max(tree[node * 2].left, tree[node * 2].sum + tree[(node * 2) + 1].left);
  34. tree[node].right = max(tree[(node * 2) + 1].right, tree[(node * 2) + 1].sum + tree[node * 2].right);
  35. tree[node].best = max(tree[node * 2].right + tree[(node * 2) + 1].left, max(tree[node * 2].best, tree[(node * 2) + 1].best));
  36. tree[node].sum = tree[node * 2].sum + tree[(node * 2) + 1].sum;
  37. return;
  38. }
  39.  
  40. ll quary(int node, int start, int endd, int l, int r)
  41. {
  42. if (start > r || endd < l)return -1000000;
  43. if (start >= l && endd <= r)return tree[node].best;
  44. int mid = (start + endd) / 2;
  45. return max(max(quary(node * 2, start, mid, l, r), quary((node * 2) + 1, mid + 1, endd, l, r)), quary(node * 2, start, mid, l, r) + quary((node * 2) + 1, mid + 1, endd, l, r));
  46. }
  47.  
  48. int main()
  49. {
  50. int n;
  51. scanf("%d", &n);
  52. for (int i = 1; i <= n; i++) {
  53. scanf("%d", &a[i]);
  54. }
  55. build_tree(1, 1, n);
  56. int m, l, r;
  57. scanf("%d", &m);
  58. while (m--) {
  59. scanf("%d %d",&l,&r);
  60. if (l > r)
  61. swap(l, r);
  62. ll ans = quary(1, 1, n , l, r);
  63. printf("%lld\n", ans);
  64. }
  65. return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement