1. 문제




5
0 0 0 0 0
0 0 1 0 3
0 2 5 0 1
4 2 4 4 2
3 5 1 3 1
8
1 5 3 5 1 2 1 4
1) 풀이
package inflearn.algorithm.stack;
import java.util.*;
public class Algorithm39 {
public int solution(int[][] arr, int[] moves){
int answer = 0;
Stack<Integer> basket = new Stack<>();
for(int pos: moves){
for(int i = 0; i < arr.length; i++){
if (arr[i][pos - 1] != 0) {
int tmp = arr[i][pos - 1];
arr[i][pos - 1] = 0;
if (!basket.isEmpty() && basket.peek() == tmp) {
answer += 2;
basket.pop();
} else {
basket.push(tmp);
}
break;
}
}
}
return answer;
}
public static void main(String[] args){
Algorithm39 T = new Algorithm39();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] arr = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = sc.nextInt();
}
}
int m = sc.nextInt();
int[] moves = new int[m];
for (int i = 0; i < m; i++) {
moves[i] = sc.nextInt();
}
System.out.println(T.solution(arr, moves));
}
}