반응형

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

 

1504번: 특정한 최단 경로

첫째 줄에 정점의 개수 N과 간선의 개수 E가 주어진다. (2 ≤ N ≤ 800, 0 ≤ E ≤ 200,000) 둘째 줄부터 E개의 줄에 걸쳐서 세 개의 정수 a, b, c가 주어지는데, a번 정점에서 b번 정점까지 양방향 길이 존

www.acmicpc.net

 

 

[ 문제풀이 ]

 

쉬운 다익스트라 문제였습니다.

 

다만 경로를 쪼개서 구해야 했고, 경우의 수가 두 가지가 있기 때문에 두 번의 계산 중 더 작은 값이 답이 되었습니다.

 

1 -> v1 -> v2 -> N

1 -> v2 -> v1 -> N

 

이 두가지 경우 중 더 거리가 짧은 경우가 답이 됩니다.

 

[ 소스 코드 ]

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <iostream>
#include <queue>
#include <vector>
 
using namespace std;
 
struct Node {
    int to;
    int cost;
};
 
struct cmp {
    bool operator()(Node right, Node left)
    {
        return left.cost < right.cost;
    }
};
 
int N, E;
vector<Node> list[801];
int v[2];
 
int dijkstra(int start, int end)        //시작점과 도착점의 최단거리를 return하는 dijkstra함수
{
    priority_queue<Node, vector<Node>, cmp> pq;
    pq.push({ start, 0 });
    int visited[801= { 0 };
 
    while (!pq.empty())
    {
        int to = pq.top().to;
        int cost = pq.top().cost;
        pq.pop();
 
        if (visited[to] == 1continue;
        visited[to] = 1;
 
        if (to == end)
        {
            return cost;
        }
 
        for (int i = 0; i < list[to].size(); i++) {
            int next = list[to][i].to;
            int nextCost = list[to][i].cost;
            if (visited[next] != 1) {
                pq.push({ next, cost + nextCost });
            }
        }
    }
 
    return -1;
}
 
int main()
{
    cin >> N >> E;
 
    for (int i = 0; i < E; i++) {
        int a, b, c;
        scanf("%d %d %d"&a, &b, &c);
        list[a].push_back({ b,c });
        list[b].push_back({ a,c });
    }
 
    for (int i = 0; i < 2; i++) {
        cin >> v[i];
    }
 
    int a1 = dijkstra(1, v[0]);
    int b1 = dijkstra(1, v[1]);
    int mid = dijkstra(v[0], v[1]);
    int a2 = dijkstra(v[1], N);
    int b2 = dijkstra(v[0], N);
 
    int min = a1 + mid + a2;        //1 -> v[0] -> v[1] -> N
 
    if (a1 != -1 && a2 != -1 && mid != -1) {
        if (min > b1 + mid + b2) {    //1 -> v[1] -> v[0] -> N
            min = b1 + mid + b2;
        }
    }
    else {        //경로가 없다면
        cout << -1;
        return 0;
    }
 
    cout << min;
}
cs
반응형

+ Recent posts