크레인 인형뽑기 (Stack)

 

import java.util.Scanner;
import java.util.Stack;

public class Main {
	
	public int solution(int l, int n, int[][] board, int[] moves) {
		int ans = 0;
		
		Stack<Integer> stk = new Stack<>();
		
		for(int x : moves) {
			for(int i = 0; i < l; i++) {
				if(board[i][x-1] != 0) {
					int temp = board[i][x-1];
					board[i][x-1] = 0;
					
					if(stk.isEmpty()) {
						stk.push(temp);
					}
					else if(!stk.isEmpty() && stk.peek()==temp) {
						stk.pop();
						ans += 2;
					}
					else {
						stk.push(temp);
					}
					break;
				}
			}
		}
		
		return ans;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Main T = new Main();
		Scanner kb = new Scanner(System.in);
		
		int l = kb.nextInt();
		int[][] board = new int[l][l];
		for(int i = 0; i < l; i++) {
			for(int j = 0; j < l; j++) {
				board[i][j] = kb.nextInt();  
			}
		}
					
		int n = kb.nextInt();
		int[] moves = new int[n];
		for(int i = 0; i < n; i++) moves[i] = kb.nextInt();  

		System.out.println(T.solution(l, n, board, moves));
	}

}

'[Solved] > 코딩테스트' 카테고리의 다른 글

토마토(BFS 활용)  (0) 2023.03.29
후위연산식 문제 (Stack)  (0) 2023.03.18
임시반장 정하기 문제  (0) 2023.03.17
Least Recently Used  (0) 2023.03.14
쇠막대기 절단 문제 (Stack)  (0) 2023.03.13