BOJ 13305 : 주유소(Java)

박철민·2023년 4월 13일
0

알고리즘 풀이

목록 보기
10/13

풀이

아이디어

간단하게 여태까지 만난 주요소 중에 가장 최저값들을 기록하면 됩니다.

다음과 같은 예제에서 보면 여태 만난 주요소 중에 최저값들을 기록하면 다음과 같을 겁니다.

위치거리현 유가최저값
1255
2322
3142
4011

이를 간단하게 거리 * 최저값의 합으로 문제를 풀 수 있습니다.

상세구현

이 코드에서 상세하게 구현할 부분은 기록하면서 최저값을 계속 보는 것입니다.

		st = new StringTokenizer(br.readLine());
		int min = 1_000_000_000;
		for(int i=0; i<N; i++) {
			int oil = Integer.parseInt(st.nextToken());
			min = Math.min(min, oil);
			cost[i] = min;
		}

다음과 같이 값을 계속 넣어줍니다.

		long sum = 0L;
		
		for(int i=0; i<N; i++) {
			sum += (long) dist[i] * cost[i];
		}
		System.out.println(sum);

계속 합을 구해주면 문제는 해결!

코드


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class No13305 {
	static int N;
	static int[] dist;
	static int[] cost;
	public static void main(String[] args) throws IOException {
		input();
		pro();
	}
	private static void pro() {
		long sum = 0L;
		
		for(int i=0; i<N; i++) {
			sum += (long) dist[i] * cost[i];
		}
		System.out.println(sum);
	}
	private static void input() throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		N = Integer.parseInt(br.readLine());
		
		dist = new int[N];
		cost = new int[N];
		
		StringTokenizer st = new StringTokenizer(br.readLine());
		for(int i=0; i<N-1; i++) {
			dist[i] = Integer.parseInt(st.nextToken());
		}
		
		st = new StringTokenizer(br.readLine());
		int min = 1_000_000_000;
		for(int i=0; i<N; i++) {
			int oil = Integer.parseInt(st.nextToken());
			min = Math.min(min, oil);
			cost[i] = min;
		}
		
		br.close();		
	}
}
profile
멘땅에 헤딩하는 사람

0개의 댓글