-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGSS1.cpp
More file actions
77 lines (65 loc) · 1.89 KB
/
Copy pathGSS1.cpp
File metadata and controls
77 lines (65 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <stdio.h>
using namespace std;
long A[50000];
int n;
struct Node
{
long MaxPrefixSum, MaxSuffixSum, Max, Total;
}SegTree[200000];
void Merge(Node& Ans, Node& Left, Node& Right)
{
Ans.MaxPrefixSum = max(Left.MaxPrefixSum, max(Left.Total, Left.Total + Right.MaxPrefixSum));
Ans.MaxSuffixSum = max(Right.MaxSuffixSum, max(Right.Total, Right.Total + Left.MaxSuffixSum));
Ans.Total = Left.Total + Right.Total;
Ans.Max = max(Ans.MaxPrefixSum, max(Ans.MaxSuffixSum, max(Ans.Total, max(Left.MaxSuffixSum + Right.MaxPrefixSum, max(Left.Max, Right.Max)))));
}
void Build(int i, int x, int y) //i, x, and y follow 1-based indexing
{
if (x == y)
SegTree[i-1].MaxPrefixSum = SegTree[i-1].MaxSuffixSum = SegTree[i-1].Max = SegTree[i-1].Total = A[x-1];
else
{
int m = (x + y)/2;
Build(2*i, x, m);
Build(2*i+1, m+1, y);
Merge(SegTree[i-1], SegTree[2*i - 1], SegTree[2*i]);
}
}
Node Query(int i, int STx, int STy, int x, int y) //i, x, and y follow 1-based indexing
{
if (STx >= x && STy <= y) //all required data is in current index
return SegTree[i-1];
else
{
int STm = (STx + STy)/2;
//left child interval: STx - STm. right child interval: STm+1 - STy.
if (x <= STm && STx <= y && y >= STm+1 && STy >= x) //need data from left and right of current node
{
Node Ans, AnsL = Query(2*i, STx, STm, x, y), AnsR = Query(2*i+1, STm+1, STy, x, y);
Merge(Ans, AnsL, AnsR);
return Ans;
}
else if (x <= STm && STx <= y) //all required data is on the left
return Query(2*i, STx, STm, x, y);
else if (y >= STm+1 && STy >= x) //all required data is on the right
return Query(2*i+1, STm+1, STy, x, y);
}
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%ld", &A[i]);
Build(1, 1, n);
int M, x, y;
scanf("%d", &M);
while (M--)
{
scanf("%d %d", &x, &y);
long Q = Query(1, 1, n, x, y).Max;
printf("%ld", Q);
printf("\n");
}
return 0;
}