Jun's Development Journey

[BOJ] 1138번 한 줄로 서기 본문

BOJ/Etc

[BOJ] 1138번 한 줄로 서기

J_Jayce 2021. 3. 15. 22:57

문제

www.acmicpc.net/problem/1138

 

1138번: 한 줄로 서기

첫째 줄에 사람의 수 N이 주어진다. N은 10보다 작거나 같은 자연수이다. 둘째 줄에는 키가 1인 사람부터 차례대로 자기보다 키가 큰 사람이 왼쪽에 몇 명이 있었는지 주어진다. i번째 수는 0보다

www.acmicpc.net

풀이

1) 처음에 짠 비효율적인 코드 (메모리 : 20128KB, 시간 : 616ms)

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

public class Main {
	static int N;
	static int[] left_bigger,tmp,heights;
	static boolean visited[],chk;
	static void dfs(int st, int depth, int std) {
		if(depth==std) {
//			for(int i=1;i<=N;i++)
//				System.out.print(tmp[i]+" ");
//			System.out.println();
			if(left_bigger[tmp[1]]==0) {
				int tc=1;
				for(int i=2;i<=N;i++) {
					int height = tmp[i];
					int cnt=0;
					for(int j=i-1;j>0;j--) {
						if(tmp[j]>height)
							cnt++;
					}
					if(cnt==left_bigger[height])
						tc++;
				}
				if(tc==N) {
					chk = true;
					for(int i=1;i<=N;i++)
						System.out.print(tmp[i]+" ");
				}
			}
			return;
		}
		for(int i=1;i<=N;i++) {
			if(!visited[i]) {
				visited[i] = true;
				tmp[depth] = heights[i];
				dfs(i+1,depth+1,std);
				visited[i] = false;
			}
		}
	}
	public static void main(String[] args) throws IOException {
        //선언 및 입력
    	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    	StringTokenizer st;
    	StringBuilder sb = new StringBuilder();
    	N = Integer.parseInt(br.readLine());
    	left_bigger = new int[N+1];
    	tmp = new int[N+1];
    	heights = new int[N+1];
    	visited = new boolean[N+1];
    	
    	st = new StringTokenizer(br.readLine());
    	for(int i=1;i<=N;i++) {
    		left_bigger[i] = Integer.parseInt(st.nextToken());
    		heights[i] = i;
    	}
    		
    	
    	//계산
    	dfs(1,1,N+1);
	}
} 

 

2) 효율적인 코드(메모리 : 16352KB, 시간 : 152ms)

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));
    	StringTokenizer st;
    	StringBuilder sb = new StringBuilder();
    	int N = Integer.parseInt(br.readLine());
    	ArrayList<Integer> list = new ArrayList<Integer>();
    	ArrayList<Integer> left = new ArrayList<Integer>();
    	st = new StringTokenizer(br.readLine());
    	for(int i=0;i<N;i++)
    		left.add(Integer.parseInt(st.nextToken()));
    	
    	//계산
    	for(int i=N;i>0;i--) {
    		list.add(left.get(i-1),i);
    	}
    	for(int num : list)
    		System.out.print(num+" ");
	}
} 

'BOJ > Etc' 카테고리의 다른 글

[BOJ] 13414번 수강신청  (0) 2021.04.22
[BOJ] 1662 압축  (0) 2021.03.19
[BOJ] 1725 히스토그램  (0) 2021.03.05