반응형
1238번: 파티
첫째 줄에 N(1 ≤ N ≤ 1,000), M(1 ≤ M ≤ 10,000), X가 공백으로 구분되어 입력된다. 두 번째 줄부터 M+1번째 줄까지 i번째 도로의 시작점, 끝점, 그리고 이 도로를 지나는데 필요한 소요시간 Ti가 들어
www.acmicpc.net
◎ 문제풀이
다익스트라 알고리즘 문제로 알려져 있는데, 문제를 보니 플로이드 워셜 알고리즘이 더 어울린다고 생각했다. 시작점이 정해져 있지 않았고 모든 노드를 기준으로 하기 때문이다. 플로이드 워셜은 삼중for문을 구현하므로 시간초과를 조심해야 하는데, 시간제한이 1초이고 n이 1000이하라 삼중for문을 돌리면 얼추 시간초과가 걸리지 않는다고 생각했다.
[Algorithm] 플로이드-워셜(Floyd-Warshall) 알고리즘이란?
[Algorithm] 다익스트라 알고리즘(Dijkstra)이란? 다익스트라 알고리즘(Dijkstra) 다익스트라 알고리즘은 특정지점에서 다른지점으로 가는 최단경로를 구하는 알고리즘이다. 다익스트라 알고리즘은 그
lordofkangs.tistory.com
알고리즘은 위 포스팅을 참고하면 된다. 참고로 int 정수 범위를 신경쓰지 않아서 몇번 틀렸다. 그래프에 무한대를 넣을때 Integer.MAX_VALUE를 사용했다. 문제는 int의 최대값과 최대값을 더해서 다시 int에 넣는 실수를 했다. int의 최댓값을 사용할때는 연산에 유의해야 겠다.
◎ 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import static java.lang.Math.*;
//BOJ1238 파티
public class Main {
static int[][] graph;
static int n;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int x = Integer.parseInt(st.nextToken());
graph = new int[n+1][n+1];
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(i==j) graph[i][j] = 0;
else graph[i][j] = 1000000000;
}
}
for(int i=0;i<m;i++){
st = new StringTokenizer(br.readLine());
int start = Integer.parseInt(st.nextToken());
int end = Integer.parseInt(st.nextToken());
int value = Integer.parseInt(st.nextToken());
graph[start][end] = value;
}
for(int mid=1;mid<=n;mid++){
for(int start=1;start<=n;start++){
for(int end=1;end<=n; end++){
int curr = graph[start][end];
int value = graph[start][mid] + graph[mid][end];
graph[start][end] = min(curr,value);
}
}
}
int ans = 0;
for(int i=1;i<=n;i++){
ans = max(ans, graph[i][x] + graph[x][i] );
}
System.out.println(ans);
}
}
반응형
'문제풀이 > ShortestPath' 카테고리의 다른 글
[PS] BOJ10159 저울 ( Floyd-warshall ) with JAVA (0) | 2023.09.28 |
---|---|
[PS] BOJ11404 플로이드 ( Floyd-Warshall ) with JAVA (0) | 2023.09.14 |
[PS] BOJ1753 최단경로 ( ShortestPath ) with JAVA (0) | 2023.07.25 |
[CodingTest] BOJ111724 연결요소 ( DFS, UNION-FIND ) With 파이썬 (0) | 2023.06.19 |
[CodingTest] 전보 ( 최단거리 ) (0) | 2023.06.01 |