SOLUTION INFO
C++ · main.cpp
- 작성자
- tony9402
- 공동 작성자
- 없음
#include<bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int N, M; cin >> N >> M;
vector<vector<pair<int, int>>> G(N + 1);
for(int i = 0; i < M; ++i) {
int u, v, w; cin >> u >> v >> w;
G[u].emplace_back(v, w);
G[v].emplace_back(u, w);
}
int S, T; cin >> S >> T;
priority_queue<pair<int, int>> pq;
const int INF = 0x3f3f3f3f;
vector<int> dist(N + 1, INF);
dist[S] = 0;
pq.emplace(0, S);
while(!pq.empty()) {
auto [d, cur] = pq.top(); pq.pop();
if(dist[cur] != -d) continue;
for(auto [nxt, w]: G[cur]) {
if(dist[nxt] > dist[cur] + w) {
dist[nxt] = dist[cur] + w;
pq.emplace(-dist[nxt], nxt);
}
}
}
cout << dist[T];
return 0;
}
SOLUTION DESCRIPTION
풀이 설명
풀이과정
```
MST 문제처럼 보이지만 조금 다른건 S랑 T가 연결될때까지 한다.
그러면 S에서 T로 가는 길에 존재하는 모든 가중치의 합 중 최솟값을 구하면 되는거 아닌가?
근데 연결되어 있다는 보장은? 연결 그래프 보장이니깐 되어 있다.
그럼 그냥 다익 돌리면 되는데?
```
SOLUTION INFO
Java · Main.java
- 작성자
- beberiche
- 공동 작성자
- 없음
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
FastReader rd = new FastReader();
int N = rd.nextInt();
int M = rd.nextInt();
List<int[]> list[] = new ArrayList[N + 1];
for (int i = 1; i <= N; i++) {
list[i] = new ArrayList<>();
}
for (int i = 0; i < M; i++) {
int a = rd.nextInt();
int b = rd.nextInt();
int c = rd.nextInt();
list[a].add(new int[]{b, c});
list[b].add(new int[]{a, c});
}
int st = rd.nextInt();
int ed = rd.nextInt();
PriorityQueue<int[]> pq = new PriorityQueue<>((n1, n2) -> n1[1] - n2[1]);
int[] dist = new int[N + 1];
int INF = (int) 1e9;
Arrays.fill(dist, INF);
pq.add(new int[]{st, 0});
dist[st] = 0;
while (!pq.isEmpty()) {
int[] curr = pq.poll();
if (curr[0] == ed) break;
for (int[] next : list[curr[0]]) {
if (dist[next[0]] > curr[1] + next[1]) {
dist[next[0]] = curr[1] + next[1];
pq.add(new int[]{next[0], dist[next[0]]});
}
}
}
System.out.println(dist[ed]);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
SOLUTION DESCRIPTION
풀이 설명
1. 다익스트라 기본 문제. 문제의 내용 그대로 임의의 지점 `s->t` 까지의 최단 경로를 구하는 문제이다.
2. 양방향의 인접 리스트와 `dist[]` 을 생성하여,
우선순위 큐를 이용해 `s` 를 시작으로 `t` 까지 도달하기까지 최소 거리를 갱신한다.