[C++] 백준 1504 : 특별한 최단 경로
Updated:
백준 1504번 문제를 풀어보았다.

1. 문제 설명

Dijkstra를 사용하여 푸는 문제.- 반드시 두 정점을 지나는 최단 경로 + 방향성이 없는 그래프 + 최단 경로
2. 문제 풀이
2.1 사용 변수
vector<info> weight[801];
int d[801];
weight- <to_node, weight>으로 저장.
weight[a][i]={b, 10}이라면 a에서 b로 가는 가중치가 10
d- 시작 노드에서부터의 최단 거리를 저장
2.2 Solution
- 주어진 노드
v1,v2를 지나는 경우- 1~
v1~v2~N - N~
v2~v1~N
- 1~
priority_queue를 이용하여 가장 짧은 간선부터 선택하여 Dijkstra로 최단 거리를 구하면 된다.
2.3 전체 코드
/*반드시 두 정점을 지나는 최단 경로(Dijkstra)*/
#include <iostream>
#include <queue>
#include <functional>
#include <vector>
#include <cstring>
using namespace std;
#define min(a,b) (a < b ? a : b)
typedef pair<int,int> info; //info : <distance,node> || <to_node, weight>
vector<info> weight[801];
const int INF = 800001;
int N;
int center=INF;
int Dijkstra(int s, int n) {
priority_queue<info, vector<info>, greater<info> > pq; //min heap
int d[801];
for (int i = 1; i < N+1; i++) d[i] = INF;
pq.push(pair<int, int>(0, s));
d[s] = 0;
int c_node;
while (!pq.empty()) {
c_node = pq.top().second;
//d[c_node] = pq.top().first; -> 예전에 들어간 업데이트되지 않은 최신 길이일 수도 있음
pq.pop();
for (int de = 0; de < weight[c_node].size();de++) { //c_node에 연결된 모든 노드들 확인
int to_node = weight[c_node][de].first;
if (d[to_node] > d[c_node] + weight[c_node][de].second) { //현재 저장된 to_node까지의 최단거리 > c_node까지의 최단거리 + c_node~to_node 사이의 거리
d[to_node] = d[c_node] + weight[c_node][de].second;
pq.push(make_pair(d[to_node], to_node));
}
}
}
return d[n];
}
int judge(int v1, int v2) { //1~v1~v2~N까지의 거리를 계산
int total = 0;
int part1, part2;
part1 = Dijkstra(1, v1);
if(center==INF) center = Dijkstra(v1, v2);
part2 = Dijkstra(v2, N);
if (part1 == INF || center == INF || part2 == INF) return -1;
total = part1 + center + part2;
return total;
}
int main() {
int E; //the num of node, the num of edge
int v1, v2; //two vertex(node) should be visited
cin >> N >> E;
/*make weight matrix*/
int a, b, c;
for (int i = 0; i < E; i++) {
cin >> a >> b >> c;
weight[a].push_back(make_pair(b, c));
weight[b].push_back(make_pair(a, c));
}
/*vertex should be visited*/
cin >> v1 >> v2;
/*solution*/
int total1, total2;
total1 = judge(v1, v2); //1~v1~v2~N
total2 = judge(v2, v1); //1~v2~v1~N
/*print*/
if (total1 == -1 && total2 == -1) cout << "-1";
else if (total1 == -1) cout << total2;
else if (total2 == -1) cout << total1;
else if (total1 < total2) cout << total1;
else cout << total2;
return 0;
}
3. Review
다익스트라 문제를 많이 풀어봐야겠음. 가끔 푸니까 개념이 기억 안남.
4. 실패한 접근 방법
- pq에서 node를 꺼낼 때 d를 한 번 더 업데이트 시켰는데 이 부분에서 더 긴 가중치가 나와도 업데이트가 되어버려서 틀렸음.
Leave a comment