백준 1015 수열 정렬

·2022년 7월 31일
0

문제

P[0], P[1], ...., P[N-1]은 0부터 N-1까지(포함)의 수를 한 번씩 포함하고 있는 수열이다. 수열 P를 길이가 N인 배열 A에 적용하면 길이가 N인 배열 B가 된다. 적용하는 방법은 B[P[i]] = A[i]이다.

배열 A가 주어졌을 때, 수열 P를 적용한 결과가 비내림차순이 되는 수열을 찾는 프로그램을 작성하시오. 비내림차순이란, 각각의 원소가 바로 앞에 있는 원소보다 크거나 같을 경우를 말한다. 만약 그러한 수열이 여러개라면 사전순으로 앞서는 것을 출력한다.


Python

from sys import stdin

stdin.readline()
array_a=list(map(int, stdin.readline().strip().split()))
count=[0]*1001
for i in array_a:
    count[i]+=1

for i in range(1, 1000):
    count[i]+=count[i-1]

for i in array_a:
    print(count[i-1], end=" ")
    count[i-1]+=1

Java

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

public class Main {
    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());
        StringTokenizer st=new StringTokenizer(br.readLine());
        int[] a=new int[n];
        for(int i=0; i<n; i++)
            a[i]=(Integer.parseInt(st.nextToken()));

        int[] count=new int[1001];
        for(int i:a)
            count[i]++;
        for(int i=1; i<1001; i++)
            count[i]+=count[i-1];
        for(int i:a)
            bw.write(count[i-1]++ +" ");

        bw.flush();
    }
}

해결 과정

  1. 문제를 보자마자 Counting Sort가 떠올랐다. 다만 어떤 숫자의 배치된 인덱스를 얻을 때 count[i]로 하면 해당 숫자의 제일 뒷 인덱스를 얻으므로, count[i-1]로 해당 숫자보다 1 작은 수의 인덱스를 얻고 count[i-1]++을 해주면 오름차순으로 출력할 수 있다.

  2. 😁

profile
渽晛

0개의 댓글