반응형

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

 

20160번: 야쿠르트 아줌마 야쿠르트 주세요

첫 줄에는 정점의 개수 V(1 ≤ V ≤ 10,000)와 도로의 개수 E(0 ≤ E ≤ 100,000)가 정수로 주어진다. 그 다음 E 줄에 걸쳐 각 도로를 나타내는 세 개의 정수 (u, v, w)가 순서대로 주어진다. 이는 u 와 v(1 ≤

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. 그래프를 입력받고, vector<pair<int, int>> list[ 10001 ] 배열에 저장합니다. 

 

2. dijkstra를 이용하여 야쿠르트 아줌마의 정점별 도착 거리를 구해 저장합니다.

 

3. dijkstra를 이용하여 나의 정점별 도착 거리를 visited 배열에 저장하고, for문을 통해 돌면서 아줌마의 도착 시점보다 내 도착 시점이 빠르거나 같은 지점을 ans에 저장합니다.

 

4. 만약 어느 정점에도 도착할 수 없다면 -1을 출력하고, 그렇지 않다면 ans를 출력합니다.

 

[ 소스코드 ]

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
90
91
92
93
94
95
#include<iostream>
#include<queue>
#include<vector>
#define ll long long
 
using namespace std;
 
int V, E;
vector<pair<intint>> list[10001];
int arr[10];
ll dist[10];
int start;
ll visited[10001];
 
int dijkstra(int s, int e)
{
    fill(visited, visited + V + 111111111111);
    visited[s] = 0;
 
    priority_queue<pair<intint>vector<pair<int,int>>, greater<pair<int,int>>> pq;
 
    pq.push({ 0,s });
 
    while (!pq.empty()) {
        const int cur = pq.top().second;
        const int dist = pq.top().first;
        pq.pop();
 
        if (cur == e) {
            return dist;
        }
 
        if (visited[cur] < dist) continue;
        visited[cur] = dist;
 
        for (auto& next : list[cur]) {
            if (visited[next.second] > dist + next.first) {
                visited[next.second] = dist + next.first;
                pq.push({ visited[next.second], next.second });
            }
        }
    }
 
    return -1;
}
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    cin >> V >> E;
 
    for (int i = 0; i < E; i++) {
        int u, v, w;
        cin >> u >> v >> w;
        list[u].push_back({ w,v });
        list[v].push_back({ w,u });
    }
 
    for (int i = 0; i < 10; i++) {
        cin >> arr[i];
    }
 
    cin >> start;
 
    int cnt = 1;
 
    for (int i = 0; i < 9; i++) {
        int next = dijkstra(arr[i], arr[i + cnt]);
        while (next == -1) {
            dist[i + cnt] = -1;
            cnt++;
            if (i + cnt == 10break;
            next = dijkstra(arr[i], arr[i + cnt]);
        }
        if (i + cnt == 10break;
        dist[i + cnt] = dist[i] + dijkstra(arr[i], arr[i + cnt]);
        i = i + cnt - 1;
        cnt = 1;
    }
 
    dijkstra(start, 0);
    int ans = 111111;
 
    for (int i = 0; i < 10; i++) {
        if (visited[arr[i]] <= dist[i]) {
            ans = min(ans, arr[i]);
        }
    }
 
    if (ans == 111111cout << -1;
    else cout << ans;
}
cs
반응형

+ Recent posts