Skip to content

Commit 47d0aad

Browse files
authored
Merge pull request #546 from AlgorithmWithGod/LiiNi-coder
[20250725] BOJ / G4 / 합이 0 / 이인희
2 parents 2c988bf + aa84e7f commit 47d0aad

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
```java
2+
import java.io.BufferedReader;
3+
import java.io.InputStreamReader;
4+
import java.util.Arrays;
5+
import java.util.StringTokenizer;
6+
7+
public class Main {
8+
private static BufferedReader br;
9+
private static int n;
10+
private static int[] arr;
11+
12+
public static void main(String[] args) throws Exception {
13+
br = new BufferedReader(new InputStreamReader(System.in));
14+
n = Integer.parseInt(br.readLine());
15+
16+
arr = new int[n];
17+
StringTokenizer st = new StringTokenizer(br.readLine());
18+
for (int i = 0; i < n; i++) {
19+
arr[i] = Integer.parseInt(st.nextToken());
20+
}
21+
22+
Arrays.sort(arr);
23+
24+
long count = 0;
25+
26+
for (int i = 0; i < n - 2; i++) {
27+
int fixed = arr[i];
28+
int left = i + 1;
29+
int right = n - 1;
30+
31+
while (left < right) {
32+
int sum = fixed + arr[left] + arr[right];
33+
34+
if (sum == 0) {
35+
if (arr[left] == arr[right]) {
36+
int length = right - left + 1;
37+
count += (long) length * (length - 1) / 2;
38+
break;
39+
}
40+
41+
int leftVal = arr[left];
42+
int rightVal = arr[right];
43+
int leftCnt = 0;
44+
int rightCnt = 0;
45+
46+
while (left <= right && arr[left] == leftVal) {
47+
leftCnt++;
48+
left++;
49+
}
50+
51+
while (left <= right && arr[right] == rightVal) {
52+
rightCnt++;
53+
right--;
54+
}
55+
56+
count += (long) leftCnt * rightCnt;
57+
58+
} else if (sum < 0) {
59+
left++;
60+
} else {
61+
right--;
62+
}
63+
}
64+
}
65+
66+
System.out.println(count);
67+
}
68+
}
69+
```

0 commit comments

Comments
 (0)