본문 바로가기

코딩테스트/JAVA

[SWEA JAVA] 1267. [S/W 문제해결 응용] 10일차 - 작업순서

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV18TrIqIwUCFAZN

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

 

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;

public class Solution {
	public static int T, V, E;
	public static int[] chasu, visited;
	public static List<Integer>[] graph;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		T = 10;
		
		for(int tc = 1; tc <= T; tc++) {
			
			V = sc.nextInt();
			E = sc.nextInt();
			graph = new ArrayList[V + 1];
			chasu = new int[V + 1];
			visited = new int[V + 1];
			
			for(int i =1;i<V+1;i++) {
				graph[i] = new ArrayList<>();
			}
			
			
			for(int i =0;i<E;i++) {
				int from = sc.nextInt();
				int to = sc.nextInt();
				graph[from].add(to);
				chasu[to] += 1;
			}
			
			Queue<Integer> q = new LinkedList();
			
			for(int i = 1; i<=V;i++) {
				if(chasu[i] == 0) {
					q.offer(i);
					visited[i] = 1;
				}
			}
			
			System.out.print("#" + tc +" ");
			
			while(!q.isEmpty()) {
				int cur = q.poll();
				System.out.print(cur + " ");
				
				for(int d : graph[cur]) {
					chasu[d] -= 1;
				}
				
				for(int i = 1; i<=V;i++) {
					if(chasu[i] == 0 && visited[i] == 0) {
						q.offer(i);
						visited[i] = 1;
					}
				}
			}
			
			System.out.println();
			
		}
	}
}

 

위상 정렬을 이용해서 풀면되는 문제이다.

 

Scanner를 for문안에 넣으면 입력값을 제대로 받지 못한다. 이클립스에서만 그런다는것을 확인하고 넘어감