백준 2493 - 탑
Updated:
Java
2493 번 - 탑
문제
상근이네 반의 N명 학생들의 이름이 성적순으로 주어졌을 때, 좋은 친구가 몇 쌍이나 있는지 구하는 프로그램을 작성하시오. 좋은 친구는 등수의 차이가 K보다 작거나 같으면서 이름의 길이가 같은 친구이다.
접근 방법
구현
코드
import java.util.*;
import java.io.*;
public class Main {
    public static void main(String []args) throws IOException {        
    	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    	StringTokenizer stk;
    	int n = stoi(br.readLine());
    	int tower[] = new int[n + 1];
    	stk = new StringTokenizer(br.readLine());
    	for(int i = 1; i <= n; i++) {
    		tower[i] = stoi(stk.nextToken());
    	}
    	int result[] = new int[n+1];
    	Stack<int[]> st = new Stack<int[]>();
    	for(int i = n; i >= 1; i--) {
    		if(!st.empty() && st.peek()[0] <= tower[i]) {
    			while(!st.empty() && st.peek()[0] <= tower[i])
	    			result[st.pop()[1]] = i;
    		}
    		st.push(new int[]{tower[i],i});
    	}
    	for(int i = 1; i <= n; i++)
    		System.out.print(result[i] + " ");
    	
    	br.close();
    }
    
    static int stoi(String str) {
    	return Integer.parseInt(str);
    }
}
총평
난이도
★★★★★
