문제링크 : https://programmers.co.kr/learn/courses/30/lessons/76503
import java.util.*;
class Solution {
public static int inorder[];
public static ArrayList<Integer>adj[];
public static boolean visited[];
public static int par[];
public static void dfs(int node){
int childCnt = 0;
for(int i=0;i<adj[node].size();i++){
int next = adj[node].get(i);
if(visited[next])continue;
visited[next] = true;
childCnt++;
dfs(next);
par[next] = node;
}
inorder[node] = childCnt;
}
public static long solution(int []a, int[][]edges){
long answer = 0;
inorder = new int[a.length];
adj = new ArrayList[a.length];
visited = new boolean[a.length];
par = new int[a.length];
long copyArr[] = new long[a.length];
for(int i=0;i<a.length;i++){
adj[i] = new ArrayList<Integer>();
copyArr[i] = a[i];
}
for(int i=0;i<edges.length;i++){
int start = edges[i][0];
int end = edges[i][1];
adj[start].add(end);
adj[end].add(start);
}
visited[0] = true;
par[0] = -1;
dfs(0);
Queue<Integer> q = new LinkedList<Integer>();
for(int i=0;i<a.length;i++){
if(inorder[i]==0){
q.add(i);
}
}
while(!q.isEmpty()){
int curNode = q.poll();
int parent = par[curNode];
if(parent==-1){
if(copyArr[curNode]==0){
return answer;
}
return -1;
}
copyArr[parent] += copyArr[curNode];
answer += Math.abs(copyArr[curNode]);
inorder[parent]--;
if(inorder[parent]==0){
q.add(parent);
}
}
return answer;
}
}
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 섬 연결하기 / JAVA (0) | 2022.02.18 |
---|---|
[프로그래머스] 징검다리 건너기 / JAVA (0) | 2022.02.18 |
[프로그래머스] 여행경로 / JAVA (0) | 2022.02.18 |
[프로그래머스] 단어 변환 / JAVA (0) | 2022.02.18 |
[프로그래머스] 등굣길 / JAVA (0) | 2022.02.18 |