BOJ 14929 귀찮아 (SIB)
BOJ 14929 귀찮아 (SIB)
https://www.acmicpc.net/problem/14929
문제
\(\begin{equation} \sum_{1 \le a < b \le n} x_ax_b \end{equation}\)
입력
n과 xi가 주어짇나. n은 10만 이하ㅇ고, xi는 젗ㄹ댓값이 100이하인 정수디이다.
출력
위에서 구하란 걸 구하면 된ㄷ.
예제 입력 1
3 1 -2 3
예제 출력 1
-5
코드
문제 제목처럼 문제 설명에서도 귀찮음이 느껴지는 문제였다.
문제로 주어진 식을 전개해서 정리해보면 $x_1 * (x_2 + x_3 + … + x_n) + x_2 * (x_3 + x_4 + … + x_n) + … + x_{n-1} * (x_n)$ 이 된다.
따라서 누적합으로 문제를 해결할 수 있다.
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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int[] x = new int[N];
int[] prefixSum = new int[N];
int sum = 0;
for (int i = 0; i < N; i++) {
x[i] = Integer.parseInt(st.nextToken());
sum += x[i];
prefixSum[i] = sum;
}
long answer = 0;
for (int i = 0; i < N - 1; i++) {
answer += x[i] * (prefixSum[N - 1] - prefixSum[i]);
}
System.out.println(answer);
}
}
This post is licensed under CC BY 4.0 by the author.