P[0], P[1], ...., P[N-1]은 0부터 N-1까지(포함)의 수를 한 번씩 포함하고 있는 수열이다. 수열 P를 길이가 N인 배열 A에 적용하면 길이가 N인 배열 B가 된다. 적용하는 방법은 B[P[i]] = A[i]이다.
배열 A가 주어졌을 때, 수열 P를 적용한 결과가 비내림차순이 되는 수열을 찾는 프로그램을 작성하시오. 비내림차순이란, 각각의 원소가 바로 앞에 있는 원소보다 크거나 같을 경우를 말한다. 만약 그러한 수열이 여러개라면 사전순으로 앞서는 것을 출력한다.
첫째 줄에 배열 A의 크기 N이 주어진다. 둘째 줄에는 배열 A의 원소가 0번부터 차례대로 주어진다. N은 50보다 작거나 같은 자연수이고, 배열의 원소는 1,000보다 작거나 같은 자연수이다.
첫째 줄에 비내림차순으로 만드는 수열 P를 출력한다.
3
2 3 1
1 2 0
import sys
'''
B[P[i]] = A[i]
N= 50이라 맵 써도 될듯?
'''
def main():
inputs = map(int, sys.stdin.read().split())
n = next(inputs)
a = [(i,next(inputs)) for i in range(n)]
a.sort(key=lambda x:x[1])
p = [0]*n
for i in range(n):
p[a[i][0]] = str(i)
sys.stdout.write(" ".join(p))
if __name__ == '__main__':
main()
그냥 단순 구현 문제. 딱히 특별히 주의해야할 것은 없는듯. 그래서 최적화도 안했음. 문제 읽고 그대로 따라가면 되는 문제.
import java.io.*;
import java.util.*;
public class Main {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = br.readLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
}
static class Pair {
int index;
int value;
Pair(int index, int value){
this.index = index;
this.value = value;
}
}
public static void main(String[] args) throws IOException {
FastReader fr = new FastReader();
int n = fr.nextInt();
Pair[] pairs = new Pair[n];
int[] p = new int[n];
for (int i = 0; i < n; i++){
int value = fr.nextInt();
pairs[i] = new Pair(i, value);
p[i] = 0;
}
Arrays.sort(pairs, Comparator.comparingInt(a -> a.value));
for (int i = 0; i < n; i++){
p[pairs[i].index] = i;
}
for (int i = 0; i < n; i++){
System.out.print(p[i] + " ");
}
}
}