위상정렬과 관련된 문제입니다.
"몇몇 작업들 사이에는 선행 관계라는 게 있어서, 어떤 작업을 수행하기 위해 반드시 먼저 완료되어야 할 작업들이 있다."
앞서 수행해야 하는 작업이 우선 수행한뒤 뒤에 노드들이 수행되어야 합니다. 따라서 위상정렬 알고리즘을 활용하여 해결할 수 있습니다.
| Scanner sc = new Scanner(System.in); |
| int n = sc.nextInt(); |
| ArrayList<Integer>[] al = new ArrayList[n+1]; |
| for(int i=1; i<=n; i++) |
| al[i] = new ArrayList<>(); |
| |
| int[] work = new int[n+1]; |
| int[] d = new int[n+1]; |
| int[] indegree = new int[n+1]; |
| |
| 다음 노드로 가리키는 방향이 여러개라면 다음 노드는 이전 노드 모두를 수행한뒤 처리해야 하기 때문에 |
| 이 시간을 업데이트 해줄 배열 입니다. |
| for(int i=1; i<=n; i++) { |
| work[i] = sc.nextInt(); |
| int cnt = sc.nextInt(); |
| for(int j=0; j<cnt; j++) { |
| int k = sc.nextInt(); |
| al[k].add(i); |
| indegree[i]++; |
| |
| } |
| } |
| Queue<Integer> q= new LinkedList<>(); |
| for(int i=1; i<=n; i++) { |
| if(indegree[i] == 0) { |
| |
| q.add(i); |
| d[i] = work[i]; |
| |
| } |
| } |
| while(!q.isEmpty()) { |
| int first = q.poll(); |
| for(int s : al[first]) { |
| indegree[s]--; |
| |
| if(indegree[s]==0) { |
| q.add(s); |
| } |
| |
| if(d[s]<d[first]+work[s]) |
| d[s] = d[first]+work[s]; |
| |
| 사실상 값은 의미없는것이 아닌가? |
| } |
| } |
| int ans = Integer.MIN_VALUE; |
| for(int i=1; i<=n; i++) { |
| ans = Math.max(ans, d[i]); |
| } |
| System.out.println(ans); |
ㅡ. 통합
| import java.util.*; |
| public class Main { |
| |
| public static void main(String[] args) { |
| |
| Scanner sc = new Scanner(System.in); |
| int n = sc.nextInt(); |
| ArrayList<Integer>[] al = new ArrayList[n+1]; |
| for(int i=1; i<=n; i++) |
| al[i] = new ArrayList<>(); |
| |
| int[] work = new int[n+1]; |
| int[] d = new int[n+1]; |
| int[] indegree = new int[n+1]; |
| for(int i=1; i<=n; i++) { |
| work[i] = sc.nextInt(); |
| int cnt = sc.nextInt(); |
| for(int j=0; j<cnt; j++) { |
| int k = sc.nextInt(); |
| al[k].add(i); |
| indegree[i]++; |
| } |
| } |
| |
| Queue<Integer> q= new LinkedList<>(); |
| for(int i=1; i<=n; i++) { |
| if(indegree[i] == 0) { |
| q.add(i); |
| d[i] = work[i]; |
| } |
| } |
| |
| while(!q.isEmpty()) { |
| int first = q.poll(); |
| for(int s : al[first]) { |
| indegree[s]--; |
| if(indegree[s]==0) { |
| q.add(s); |
| } |
| if(d[s]<d[first]+work[s]) |
| d[s] = d[first]+work[s]; |
| } |
| } |
| int ans = Integer.MIN_VALUE; |
| for(int i=1; i<=n; i++) { |
| ans = Math.max(ans, d[i]); |
| } |
| System.out.println(ans); |
| } |
| } |
| |
댓글을 사용할 수 없습니다.