✔️ 내 답-> 정답->강의랑 같음 끝
import java.util.*;
public class Main {
public static int solution(int n,int[][] n_arr,int m,int[] m_arr){
int answer=0;
Stack<Integer> st= new Stack<>();
for(int x : m_arr) {
for(int i=0;i<n;i++) {
if(n_arr[i][x-1]!=0) {
//System.out.println(n_arr[i][x-1]);
if(!st.empty()&&st.peek()==n_arr[i][x-1]) {
//System.out.println(st.peek());
st.pop();
answer+=2;
}
else if( st.empty()|| st.peek()!=n_arr[i][x-1]) {
st.push(n_arr[i][x-1]);
}
n_arr[i][x-1]=0;
break;
}
}
}
return answer;
}
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
int n_arr[][] = new int[n][n];
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
n_arr[i][j]=kb.nextInt();
}
}
int m= kb.nextInt();
int[] m_arr = new int[m];
for(int i=0;i<m;i++) {
m_arr[i]=kb.nextInt();
}
System.out.println(solution(n,n_arr,m,m_arr));
}
}
public void push(Element data);//순차보관
public Element pop();//가장 최근에 보관한 값 꺼내고 반환
public Element peek();//가장 최근에 보관한 값 단순 참조, 꺼내지 않음
public boolean empty(); //비어있는지 판별
public int search(Element data); //data를 보관한 순번 반환(1부터 시작)