이번에 풀어본 문제는
백준 13305번 주유소 입니다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int N;
static long price;
static long [] roads, oils;
static boolean isDone;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine()) - 1;
roads = new long[N];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) roads[i] = Long.parseLong(st.nextToken());
oils = new long[N]; // 마지막은 버려도됨
st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) oils[i] = Long.parseLong(st.nextToken());
int idx = 0;
long currentOil = 0;
while (idx < N) {
if (isDone) break;
if (currentOil < roads[idx]) currentOil = fill(idx, currentOil);
currentOil -= roads[idx++];
}
System.out.print(price);
}
static long fill(int idx, long currentOil) {
long amount = roads[idx];
int nextStation = idx + 1;
while (nextStation < N) {
if (oils[idx] < oils[nextStation]) amount += roads[nextStation];
else break;
if (nextStation == N - 1) isDone = true;
nextStation++;
}
price += oils[idx] * amount;
return currentOil + amount;
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int N;
static long price;
static long [] roads, oils;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine()) - 1;
roads = new long[N];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) roads[i] = Long.parseLong(st.nextToken());
oils = new long[N]; // 마지막은 버려도됨
st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) oils[i] = Long.parseLong(st.nextToken());
for (int i = 0; i < N - 1; i++) {
if (oils[i] < oils[i + 1]) oils[i + 1] = oils[i];
price += (roads[i] * oils[i]);
}
price += (roads[N - 1] * oils[N - 1]); // 마지막 도시
System.out.print(price);
}
}
주어진 도로 좌측 끝에서 우측 끝까지 이동하는 데 km당 1리터의 기름이 필요합니다.
각 도시 별 주유소의 기름 값이 주어질 때, 마지막 도시까지 소비할 수 있는 기름값의 최소 비용을 출력하는 문제입니다.
1번 풀이를 사용했는데 58점이 나와서, 효율성 문제인 것 같아 다른 풀이를 찾아보았습니다.
근데, 자료형을 long으로 바꾸어주면 두 풀이 모두 통과되네요..ㅋㅋㅋㅋ
그래도 2번이 훨씬 효율적인 풀이 방법이었어서, 한번 더 공부할 수 있었습니다 ㅎㅎ