[BaekJoon] 2212 ์„ผ์„œ (Java)

SeongWon Ohยท2021๋…„ 10์›” 15์ผ
0
post-thumbnail

๐Ÿ”— ๋ฌธ์ œ ๋งํฌ

https://www.acmicpc.net/problem/2212


๐Ÿ“ ๋ฌธ์ œํ’€์ด ๋ฐฉ๋ฒ•

N๊ฐœ์˜ ์„ผ์„œ๋“ค ์‚ฌ์ด์— M๊ฐœ์˜ ์ง‘์ค‘๊ตญ์„ ์„ค์น˜ํ•˜์—ฌ M๊ฐœ์˜ ์ง‘๋‹จ์„ ๋งŒ๋“ค์—ˆ์„ ๋•Œ ๊ฐ๊ฐ ์ง‘์ค‘๊ตญ๋“ค์ด ์ปค๋ฒ„ํ•˜๋Š” ๊ฑฐ๋ฆฌ์˜ ์ตœ์†Ÿ๊ฐ’์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

ํ•˜๋‚˜์˜ ์ง‘์ค‘๊ตญ๋“ค์ด ์ปค๋ฒ„ํ•˜๋Š” ๊ฑฐ๋ฆฌ๋Š” ํ•ด๋‹น ์ง‘์ค‘๊ตญ์ด ํฌํ•จ๋œ ์ง‘ํ•ฉ์˜ ์„ผ์„œ๋“ค์‚ฌ์ด์˜ ๊ฑฐ๋ฆฌ์˜ ํ•ฉ๊ณผ ๊ฐ™๋‹ค๊ณ  ํ•  ์ˆ˜ ์žˆ๋‹ค.

๊ทธ๋ž˜์„œ ์ง‘์ค‘๊ตญ๋“ค์ด ์ปค๋ฒ„ํ•˜๋Š” ๊ฑฐ๋ฆฌ๊ฐ€ ์ตœ์†Œ๊ฐ€ ๋˜๋ ค๋ฉด ์„ผ์„œ ์‚ฌ์ด์˜ ๊ฑฐ๋ฆฌ๊ฐ€ ๊ฐ€์žฅ ๊ธด ๊ฑฐ๋ฆฌ๋ฅผ ๋‚˜๋ˆ„์–ด M๊ฐœ์˜ ์ง‘ํ•ฉ์„ ๋งŒ๋“ค๋ฉด ๋œ๋‹ค.

์ฆ‰, ์„ผ์„œ์‚ฌ์ด์˜ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•˜์—ฌ ์ •๋ ฌํ•œ ํ›„ ๊ฐ€์žฅ ๊ธธ์ด๊ฐ€ ๊ธด M-1๊ฐœ์˜ ๊ฐ’์„ 0์œผ๋กœ ๋ณ€๊ฒฝํ•ด์ฃผ๊ณ  ์„ผ์„œ์‚ฌ์ด์˜ ๊ฑฐ๋ฆฌ์˜ ํ•ฉ์„ ๊ตฌํ•˜๋ฉด ์ตœ์ข… ๊ฒฐ๊ณผ๊ฐ€ ๋œ๋‹ค.


๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ป ์ž‘์„ฑํ•œ ์ฝ”๋“œ

import java.io.*;
import java.util.*;

public class Main {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int N = Integer.parseInt(br.readLine());
		int M = Integer.parseInt(br.readLine());
		
       		// ์„ผ์„œ๋ณด๋‹ค ์ง‘์ค‘๊ตญ์ด ๋” ๋งŽ์€ ๊ฒฝ์šฐ ๊ฑฐ๋ฆฌ๋Š” 0 
		if (M >= N) {
			System.out.println(0);
			System.exit(0);
		}
		
		int[] sensor = new int[N];
		StringTokenizer st = new StringTokenizer(br.readLine());
		for (int i=0; i<N; i++) {
			sensor[i] = Integer.parseInt(st.nextToken());
		}
		Arrays.sort(sensor);

		// sensor์‚ฌ์ด์˜ ๊ฑฐ๋ฆฌ ๊ณ„์‚ฐ
		Integer[] sensorDistance = new Integer[N-1]; // sensor์‚ฌ์ด์˜ ๊ฑฐ๋ฆฌ
		for (int i=0; i<N-1; i++) {
			sensorDistance[i] = sensor[i+1] - sensor[i];
		}
		Arrays.sort(sensorDistance, Collections.reverseOrder());
		
		// ๊ฐ€์žฅ ๊ธด ๊ฑฐ๋ฆฌ M-1๊ฐœ๋ฅผ 0์œผ๋กœ ์ดˆ๊ธฐํ™”(ํ•ด๋‹น ์œ„์น˜์— ๊ธฐ์ง€๊ตญ์„ ์„ค์น˜ํ•˜๊ธฐ ๋•Œ๋ฌธ)
		for (int i=0; i<M-1; i++) {
			sensorDistance[i] = 0;
		}
		
		// ์ตœ์ข… ๊ธธ์ด ๊ตฌํ•˜๊ธฐ
		int result = 0;
		for (int i=0; i<N-1; i++) {
			result += sensorDistance[i];
		}
		
		System.out.println(result);	
	}
}

profile
๋ธ”๋กœ๊ทธ ์ด์ „ํ–ˆ์Šต๋‹ˆ๋‹ค. -> https://seongwon.dev/

0๊ฐœ์˜ ๋Œ“๊ธ€