알고리즘/다익스트라

BJ_G4_10282_해킹 - Java

naksnaks 2022. 1. 21.
반응형

 

[문제링크]

https://www.acmicpc.net/problem/10282

 

10282번: 해킹

최흉최악의 해커 yum3이 네트워크 시설의 한 컴퓨터를 해킹했다! 이제 서로에 의존하는 컴퓨터들은 점차 하나둘 전염되기 시작한다. 어떤 컴퓨터 a가 다른 컴퓨터 b에 의존한다면, b가 감염되면

www.acmicpc.net


[문제]

최흉최악의 해커 yum3이 네트워크 시설의 한 컴퓨터를 해킹했다! 이제 서로에 의존하는 컴퓨터들은 점차 하나둘 전염되기 시작한다. 어떤 컴퓨터 a가 다른 컴퓨터 b에 의존한다면, b가 감염되면 그로부터 일정 시간 뒤 a도 감염되고 만다. 이때 b가 a를 의존하지 않는다면, a가 감염되더라도 b는 안전하다.

최흉최악의 해커 yum3이 해킹한 컴퓨터 번호와 각 의존성이 주어질 때, 해킹당한 컴퓨터까지 포함하여 총 몇 대의 컴퓨터가 감염되며 그에 걸리는 시간이 얼마인지 구하는 프로그램을 작성하시오.


[입력]

첫째 줄에 테스트 케이스의 개수가 주어진다. 테스트 케이스의 개수는 최대 100개이다. 각 테스트 케이스는 다음과 같이 이루어져 있다.

  • 첫째 줄에 컴퓨터 개수 n, 의존성 개수 d, 해킹당한 컴퓨터의 번호 c가 주어진다(1 ≤ n ≤ 10,000, 1 ≤ d ≤ 100,000, 1 ≤ c ≤ n).
  • 이어서 d개의 줄에 각 의존성을 나타내는 정수 a, b, s가 주어진다(1 ≤ a, b ≤ n, a ≠ b, 0 ≤ s ≤ 1,000). 이는 컴퓨터 a가 컴퓨터 b를 의존하며, 컴퓨터 b가 감염되면 s초 후 컴퓨터 a도 감염됨을 뜻한다.

각 테스트 케이스에서 같은 의존성 (a, b)가 두 번 이상 존재하지 않는다.

 


[출력]

각 테스트 케이스마다 한 줄에 걸쳐 총 감염되는 컴퓨터 수, 마지막 컴퓨터가 감염되기까지 걸리는 시간을 공백으로 구분지어 출력한다.


[예제 입력 1]

2
3 2 2
2 1 5
3 2 5
3 3 1
2 1 2
3 1 8
3 2 4

[예제 출력 1]

2 5
3 6

 


[설명]

이 문제는 다익스트라라는 것을 인식하고 구현할 줄 아는지 확인하는 문제입니다.

첫 컴퓨터부터 시작하여 그 컴퓨터와 연결되는 컴퓨터들의 시간을 확인하며 시간이 더 짧아질 경우 시간을 최솟값으로 변경하여 주면 된다.

 

 

백준 알고리즘 10282번 JAVA풀이

 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class Main {

	static int testCase;      //테스트 케이스 수
	static int n, d, c;       //n : 컴퓨터 개수 / d : 의존성 개수 / c : 해킹당한 컴퓨터 번호
	static int[] distance;    //해당 노드까지의 거리
	static boolean[] visited; //해당 노드 방문여부
	static ArrayList<Computer>[] list; //해당 노드에서 출발하는 간선의 종류

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		testCase=Integer.parseInt(br.readLine());
		for(int i=0;i<testCase;i++) {
			st = new StringTokenizer(br.readLine());

			n=Integer.parseInt(st.nextToken());
			d=Integer.parseInt(st.nextToken());
			c=Integer.parseInt(st.nextToken());

			list = new ArrayList[n+1];
			distance=new int[n+1];
			visited=new boolean[n+1];

			for(int j=1;j<=n;j++) {
				distance[j]=Integer.MAX_VALUE;      //아직 연결되지 않았으므로 무한대 값
				list[j]=new ArrayList<>();
			}

			for(int j=0;j<d;j++) {
				st=new StringTokenizer(br.readLine());

				int a=Integer.parseInt(st.nextToken());
				int b=Integer.parseInt(st.nextToken());
				int s=Integer.parseInt(st.nextToken());
				list[b].add(new Computer(a,s));   
			}

			distance[c]=0;      //첫 시작점에서의 거리는 0
			dijkstra();

			int cnt=0;          //총 감염되는 컴퓨터 수
			int time=0;         //마지막 컴퓨터가 감염되기까지 걸리는 시간

			for(int j=1;j<=n;j++) {
				if(distance[j] != Integer.MAX_VALUE) {
					cnt++;
					time=Math.max(time, distance[j]);
				}
			}
			System.out.println(cnt+" "+time);

		}
	}

	private static void dijkstra() {
		PriorityQueue<Computer> queue = new PriorityQueue<>();
		queue.add(new Computer(c,0));       //첫번째 컴퓨터를 queue에 추가
		while(!queue.isEmpty()) {
			int cur = queue.poll().node;
			if(!visited[cur]) {
				visited[cur]=true;

				for(Computer next: list[cur]) {     //출발지를 cur 컴퓨터로 하는 노드들 반복
					if(distance[next.node] > distance[cur] + next.time) {     //현재까지 next까지의 거리가 최소가 아니라면(cur까지의 거리 + cur에서 next까지의 거리)
						distance[next.node] = distance[cur] + next.time;        //최솟값으로 변경
						queue.add(new Computer(next.node, distance[next.node])); // queue에 추가
					}
				}
			}
		}
	}

	public static class Computer implements Comparable<Computer>{
		int node;
		int time;
		public Computer(int node, int time) {
			super();
			this.node = node;
			this.time = time;
		}

		@Override
		public int compareTo(Computer com) {
			return this.time - com.time;
		}

	}
}

 

 

 

궁금하신 부분이나 부족한 점은 댓글로 알려주시면 감사하겠습니다.

 
반응형

댓글

💲 추천 글