blog.itcode.devblog.itcode.dev

[Baekjoon / JAVA] Baekjoon Algorithm Problem 1015 - Sequence Sort

P[0], P[1], ..., P[N - 1] is a sequence containing each of the numbers from 0 to N - 1 (inclusive) exactly once. Applying sequence P to an array A of length N produces an array B of length N. The method of application is B[P[i]] = A[i]. Given array A, write a program that finds the sequence P such that the result of applying P is non-decreasing. Non-decreasing means each element is greater than or equal to the element immediately before it. If there are multiple such sequences, print the one that comes first in lexicographic order.

[Baekjoon / JAVA] Baekjoon Algorithm Problem 1015 - Sequence Sort

P[0], P[1], ..., P[N - 1] is a sequence containing each of the numbers from 0 to N - 1 (inclusive) exactly once. Applying sequence P to an array A of length N produces an array B of length N. The method of application is B[P[i]] = A[i]. Given array A, write a program that finds the sequence P such that the result of applying P is non-decreasing. Non-decreasing means each element is greater than or equal to the element immediately before it. If there are multiple such sequences, print the one that comes first in lexicographic order.
RWB0104
@RWBwritten at 2021-06-21 16:23:31
Baekjoon Algorithm

시리즈 모아보기

Baekjoon Algorithm

17 / 22
RankLanguage Used

🖼️ JAVA

🔗 Full Problem 1015

Time LimitMemory Limit
2 sec128MB

P[0],P[1],P[N1]P[0], P[1], \, \dots \, P[N - 1] is a sequence containing each of the numbers from 00 to N1N - 1 (inclusive) exactly once. Applying sequence PP to an array AA of length NN produces an array BB of length NN. The method of application is B[P[i]]=A[i]B[P[i]] = A[i].

Given array AA, write a program that finds the sequence PP such that the result of applying PP is non-decreasing. Non-decreasing means each element is greater than or equal to the element immediately before it. If there are multiple such sequences, print the one that comes first in lexicographic order.

The first line gives the size NN of array AA. The second line gives the elements of array AA, starting from index 0 in order. NN is a natural number less than or equal to 50, and each element of the array is a natural number less than or equal to 1,000.

On the first line, print the sequence PP that makes the result non-decreasing.

  • Input

TC

3
2 3 1
  • Output

TC

1 2 0

If you know sorting well, this is an easy breather of a problem. In short, all you need to do is convert the elements in the array into their rank by size, and mark that rank in the same position.

In the example, array AA is given as [2,3,1][ 2, 3, 1 ]. Sorting this in ascending order gives array A1=[1,2,3]A1 = [ 1, 2, 3 ]. In other words, A1[0]=1A1[0] = 1. The algorithm's final step is to output the index of A1A1 in the order that matches the original elements of AA.

First, sorting an integer array in ascending order is very easy — all you need is Arrays.sort(A);. The problem is that you need to output the sorted indices in the order of the original array AA.

To keep track of this, we turn array AA into a 2D array, storing the value of the i-th input in A[i][0]A[i][0] and the index i in A[i][1]A[i][1].

This can be diagrammed in a table as follows.

ii012
A[i][0]A[i][0]231
A[i][1]A[i][1]012

This way, even after sorting array AA, we can still remember the original order.

ii012
A[i][0]A[i][0]123
A[i][1]A[i][1]201

The table above shows the result after applying an ascending sort. We can use A[i][1]A[i][1] to restore the original order.

We compute BB, the result of applying sequence PP to array AA. Since we already computed the rank by size through sorting above, all that's left is to put things back into position and print them.

The original position value is held by A[i][1]A[i][1], so let's use that index. The formula for array BB can be computed in the form B[A[i][1]]=iB[A[i][1]] = i. For example, when i=1i = 1, the sorted value A[1][1]=0A[1][1] = 0, so B[0]=1B[0] = 1. Implementing this in code completes the solution.

There's one small snag here — sorting itself. The go-to sorting method, Arrays.sort(A);, works as intended for a 1D array, but for arrays of 2 or more dimensions, it doesn't behave as intended. Also, Arrays.sort(A); only ever sorts in ascending order.

To solve this, you can override the sort() method directly. Of course, you could implement it entirely from scratch, but here we make the most of the base API and override the sort function to fit our intent.

JAVA

Arrays.sort(A, (next, current) -> {
	// 다음 원소가 현재 원소보다 클 경우
	if (next[0] < current[0])
	{
		// 현재 원소를 다음 원소의 뒤로 정렬
		return 1;
	}

	// 다음 원소가 현재 원소보다 작을 경우
	else if (next[0] > current[0])
	{
		// 현재 원소를 다음 원소의 앞으로 정렬
		return -1;
	}

	// 다음 원소가 현재 원소와 동일할 경우
	else
	{
		// 현 위치 유지
		return 0;
	}
})

This is code that implements the Comparator interface in the form of a lambda function. current refers to the current element, and next refers to the next element. If the return value is positive, the current element is sorted after the next element, and if the return value is negative, the current element is sorted before the next element.

JAVA

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;

/**
 * 백준 전체 1015 문제 알고리즘 클래스
 *
 * @author RWB
 * @see <a href="https://blog.itcode.dev/posts/2021/06/22/a1015">1015 풀이</a>
 * @since 2021.06.22 Tue 01:23:31
 */
public class Main
{
	/**
	 * 메인 함수
	 *
	 * @param args: [String[]] 매개변수
	 *
	 * @throws IOException 데이터 입출력 예외
	 */
	public static void main(String[] args) throws IOException
	{
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
		
		// 배열의 크기
		int N = Integer.parseInt(reader.readLine());
		
		// 원본 배열
		int[][] A = new int[N][2];
		
		// 정렬 배열
		int[] B = new int[N];
		
		String[] temp = reader.readLine().split(" ");
		
		StringBuilder builder = new StringBuilder();
		
		for (int i = 0; i < N; i++)
		{
			A[i][0] = Integer.parseInt(temp[i]);
			A[i][1] = i;
		}
		
		// 정렬 수행
		sort(A);
		
		for (int i = 0; i < N; i++)
		{
			int index = A[i][1];
			
			B[index] = i;
		}
		
		for (int b : B)
		{
			builder.append(b).append(" ");
		}
		
		System.out.println(builder.toString().trim());
		
		writer.close();
		reader.close();
	}
	
	/**
	 * 정렬 함수
	 *
	 * @param A: [int[][]] 대상 배열
	 */
	private static void sort(int[][] A)
	{
		Arrays.sort(A, (next, current) ->
		{
			// 현재값이 더 클 경우
			if (next[0] < current[0])
			{
				return -1;
			}
			
			// 다음값이 더 클 경우
			else if (next[0] > current[0])
			{
				return 1;
			}
			
			// 현재값과 다음값이 같을 경우, 사전순 정렬
			else
			{
				return Integer.compare(next[1], current[1]);
			}
		});
	}
}
  • Sorting
# Baekjoon# Algorithm# JAVA# SILVER# SILVER IV# Sorting
ship
blog.itcode.dev

Notes from the π-th Alpaca

7.0.1
Developed by RWB since 2021.057th upgraded at 2026.08