Skip to content

Commit 4e1f500

Browse files
authored
Merge pull request #178 from AlgorithmWithGod/ShinHeeEul
[20250225] BOJ / P5 / 부분배열 고르기 / 신희을
2 parents e16d06d + 80e2579 commit 4e1f500

File tree

1 file changed

+109
-0
lines changed

1 file changed

+109
-0
lines changed
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
```java
2+
import java.util.Arrays;
3+
4+
public class Main {
5+
6+
static long[] sums;
7+
static Node[] segments;
8+
static int size;
9+
static int N;
10+
static long max;
11+
12+
static Node MAX_NODE = new Node(-1, Integer.MAX_VALUE);
13+
14+
public static void main(String[] args) throws Exception {
15+
16+
N = read();
17+
size = 1;
18+
sums = new long[N + 1];
19+
20+
while(size < N) {
21+
size <<= 1;
22+
}
23+
24+
segments = new Node[(size << 1) + 1];
25+
Arrays.fill(segments, MAX_NODE);
26+
for(int i = size + 1; i < size + N + 1; i++) {
27+
int a = read();
28+
int b = i - size;
29+
sums[b] = a + sums[b - 1];
30+
segments[i] = new Node(b, a);
31+
}
32+
33+
int segmentSize = (size << 1);
34+
35+
while(segmentSize > 1) {
36+
Node a = segments[segmentSize - 1];
37+
Node b = segments[segmentSize];
38+
int c = segmentSize >> 1;
39+
if(a.min < b.min) {
40+
segments[c] = a;
41+
} else {
42+
segments[c] = b;
43+
}
44+
segmentSize -= 2;
45+
}
46+
47+
backTracking(1, N);
48+
System.out.println(max);
49+
}
50+
51+
public static void backTracking(int start, int end) {
52+
if(start > end || start <= 0 || start > N || end > N) return;
53+
Node node = query(start, end, 2, 1, size);
54+
55+
max = Math.max(max, node.min * (sums[end] - sums[start - 1]));
56+
57+
if(end == start) return;
58+
int index = node.index;
59+
backTracking(start, index - 1);
60+
backTracking(index + 1, end);
61+
}
62+
63+
public static Node query(int left, int right, int node, int start, int end) {
64+
if(end < left || right < start) return MAX_NODE;
65+
66+
if(left <= start && end <= right) {
67+
return segments[node];
68+
}
69+
70+
int mid = (start + end) >> 1;
71+
int halfNode = (node << 1);
72+
Node a = query(left, right, halfNode - 1, start, mid);
73+
Node b = query(left, right, halfNode, mid + 1, end);
74+
75+
if(a.min < b.min) {
76+
return a;
77+
}
78+
return b;
79+
}
80+
81+
public static class Node {
82+
int index;
83+
int min;
84+
85+
Node(int index, int min) {
86+
this.index = index;
87+
this.min = min;
88+
}
89+
}
90+
91+
private static int read() throws Exception {
92+
int d, o;
93+
boolean negative = false;
94+
d = System.in.read();
95+
96+
if (d == '-') {
97+
negative = true;
98+
d = System.in.read();
99+
}
100+
o = d & 15;
101+
102+
while ((d = System.in.read()) > 32)
103+
o = (o << 3) + (o << 1) + (d & 15);
104+
105+
return negative? -o:o;
106+
}
107+
108+
}
109+
```

0 commit comments

Comments
 (0)