그리디 알고리즘
ex) N = 4
도시마다 기름 가격 5 2 4 1
도시 사이 거리 2 3 1
도시마다 비교해서 앞 도시의 기름 가격이 더 싸다면 거기서 채워넣으면 된다.
즉, 5 2 4 1 -> 5 2 2 1 로 가격을 생각하면 된다. 마지막 도시의 기름 가격은 신경쓰지 않아도 된다.
답은 5*2 + 2*3 + 2*1 = 18 이다.
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
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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());
long[] price = new long[N];
long[] distance = new long[N-1];
String[] distanceStr = br.readLine().split(" ");
String[] priceStr = br.readLine().split(" ");
for(int i=0;i<distanceStr.length;i++) {
distance[i] = Integer.parseInt(distanceStr[i]);
}
for(int i=0;i<priceStr.length;i++) {
price[i] = Integer.parseInt(priceStr[i]);
}
solved(price, distance);
}
static void solved(long[] price, long[] distance) {
long answer = 0;
for(int i=0;i<price.length-1;i++) {
if(price[i]<price[i+1]) {
price[i+1] = price[i];
}
}
for(int i=0;i<distance.length;i++) {
answer += distance[i] * price[i];
}
System.out.println(answer);
}
}
|
cs |
'Coding > 백준' 카테고리의 다른 글
1439번 뒤집기(Java) (0) | 2021.09.16 |
---|---|
1931번 회의실 배정 (0) | 2021.07.22 |
1789번 수들의 합 (java) (0) | 2021.07.07 |
1339번 단어 수학 (0) | 2021.05.20 |
10162번 전자레인지 (0) | 2021.05.08 |