Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- 복서 정렬하기
- 몯느 순열
- BOJ
- 입실 퇴실
- dfs
- BFS
- 재귀
- 백트래킹
- 줄어드는 숫자
- 너비우선탐색
- 코딩테스트
- 위클리 6주차
- 문서자동화
- DP
- 위클리 챌린지
- 1174
- ElementTree
- 백준
- openssl
- 10597
- Java
- 완전 탐색
- 프로그래머스
- 좋은 수열
- 그래프
- 백트랙킹
- 백트렉킹
- 39080
- 순열장난
- 부분 수열의 합
Archives
개발자-H 입니다.
BOJ - 최소비용 구하기 본문
https://www.acmicpc.net/problem/1916
1916번: 최소비용 구하기
첫째 줄에 도시의 개수 N(1 ≤ N ≤ 1,000)이 주어지고 둘째 줄에는 버스의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 그리고 셋째 줄부터 M+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그
www.acmicpc.net
- 최단 경로 문제이다.
- 다익스트라 알고리즘을 연습 할 수 있는 좋은 문제이다.
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main {
public static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws Exception {
int N = scanner.nextInt();
int M = scanner.nextInt();
// 도시 수
Node[] nodes = new Node[N + 1];
for (int i = 1; i <= N; i++) {
nodes[i] = new Node(i);
}
// 버스 간선 수
for (int i = 0; i < M; i++) {
int u = scanner.nextInt();
int v = scanner.nextInt();
int w = scanner.nextInt();
Edge edge = new Edge(nodes[u], nodes[v], w);
nodes[u].edges.add(edge);
}
// 출발 지 목적지
int origin = scanner.nextInt();
int dest = scanner.nextInt();
boolean[] visit = new boolean[N + 1];
int[] distance = new int[N + 1];
PriorityQueue<State> queue = new PriorityQueue<>();
queue.add(new State(nodes[origin], 0));
while (!queue.isEmpty()) {
State node = queue.poll();
if (visit[node.currentNode.index] == true) continue;
visit[node.currentNode.index] = true;
distance[node.currentNode.index] = node.totalWeight;
if(node.currentNode.index == dest) {
System.out.println(node.totalWeight);
System.exit(0);
}
for (Edge edge : node.currentNode.edges) {
Node next = edge.dest;
if (visit[next.index] == true) continue;
queue.add(new State(next, node.totalWeight + edge.weight));
}
}
}
}
class Node {
public int index;
public ArrayList<Edge> edges;
public Node(int index) {
this.index = index;
this.edges = new ArrayList<>();
}
}
class State implements Comparable<State> {
public Node currentNode;
public int totalWeight;
public State(Node currentNode, int totalWeight) {
this.currentNode = currentNode;
this.totalWeight = totalWeight;
}
@Override
public int compareTo(State other) {
return this.totalWeight - other.totalWeight;
}
}
class Edge {
public Node origin;
public Node dest;
public int weight;
public Edge(Node origin, Node dest, int weight) {
this.origin = origin;
this.dest = dest;
this.weight = weight;
}
}
'Algorithm > 문제 풀이' 카테고리의 다른 글
BOJ - 1, 2, 3 더하기 (0) | 2021.08.16 |
---|---|
BOJ - 토마토 (7576) (0) | 2021.08.14 |
BOJ - 파도반 수열 (0) | 2021.08.12 |
BOJ - 피보나치 함수 (0) | 2021.08.12 |
BOJ - N과 M (4) (0) | 2021.08.11 |
Comments