์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ/BOJ_Java

[BOJ/Step12] 10989 : ์ˆ˜ ์ •๋ ฌํ•˜๊ธฐ 3 (JAVA)

NaNaRin๐Ÿ™ƒ 2021. 1. 28. 21:08

www.acmicpc.net/problem/10989

 

10989๋ฒˆ: ์ˆ˜ ์ •๋ ฌํ•˜๊ธฐ 3

์ฒซ์งธ ์ค„์— ์ˆ˜์˜ ๊ฐœ์ˆ˜ N(1 ≤ N ≤ 10,000,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์—๋Š” ์ˆซ์ž๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ด ์ˆ˜๋Š” 10,000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ž์—ฐ์ˆ˜์ด๋‹ค.

www.acmicpc.net


๋ฌธ์ œ

N๊ฐœ์˜ ์ˆ˜๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ์ด๋ฅผ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

 

์ž…๋ ฅ

์ฒซ์งธ ์ค„์— ์ˆ˜์˜ ๊ฐœ์ˆ˜ N(1 ≤ N ≤ 10,000,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์—๋Š” ์ˆซ์ž๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ด ์ˆ˜๋Š” 10,000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ž์—ฐ์ˆ˜์ด๋‹ค.

 

์ถœ๋ ฅ

์ฒซ์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์— ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ ๊ฒฐ๊ณผ๋ฅผ ํ•œ ์ค„์— ํ•˜๋‚˜์”ฉ ์ถœ๋ ฅํ•œ๋‹ค.

 

์˜ˆ์ œ ์ž…๋ ฅ 1

10

5

2

3

1

4

2

3

5

1

7

 

์˜ˆ์ œ ์ถœ๋ ฅ 1

1

1

2

2

3

3

4

5

5

7


ํ’€์ด

์ˆ˜์˜ ๋ฒ”์œ„๊ฐ€ ์ž‘๋‹ค๋ฉด ์นด์šดํŒ… ์ •๋ ฌ์„ ์‚ฌ์šฉํ•˜๋ฉด ๋”์šฑ ๋น ๋ฅด๊ฒŒ ์ •๋ ฌํ•  ์ˆ˜ ์žˆ๋‹ค

=> ์นด์šดํŒ… ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜

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

public class B10989 {

	static void countingSort(int[] a, int n) {
		int max = a[0];
		for(int i = 0; i < n; i++) {
			if(a[i] > max)
				max = a[i];
		}
		
		int[] counting = new int[max+1];
		int[] b = new int[n];
		
		for(int i = 0; i < n; i++) counting[a[i]]++;
		for(int i = 1; i <= max; i++) counting[i] += counting[i-1];
		for(int i = n-1; i >= 0; i--) b[--counting[a[i]]] = a[i];
		for(int i = 0; i < n; i++) a[i] = b[i];
	}
	
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
		int n = Integer.parseInt(br.readLine());
		int[] sort = new int[n];
		
		for(int i = 0; i < n; i++) {
			sort[i] = Integer.parseInt(br.readLine());
		}
		
		countingSort(sort, n);		// ์นด์šดํŒ… ์ •๋ ฌ

		for(int i = 0; i < n; i++) {
			bw.write(Integer.toString(sort[i]) +"\n");
		}
		bw.flush();
	}
}