반응형

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

 

1162번: 도로포장

첫 줄에는 도시의 수 N(1 ≤ N ≤ 10,000)과 도로의 수 M(1 ≤ M ≤ 50,000)과 포장할 도로의 수 K(1 ≤ K ≤ 20)가 공백으로 구분되어 주어진다. M개의 줄에 대해 도로가 연결하는 두 도시와 도로를 통과하

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. visited[ N ][ K ] 배열을 만들어 도로를 K번 포장했을 때 해당 노드까지의 최단 거리를 저장합니다.

 

2. dijkstra를 통해 포장을 했을 때와 하지 않았을 때 각각 priority_queue에 넣어줍니다.

 

3. N번 도시에 도착했을 때 dist를 출력합니다.

 

[ 소스코드 ]

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
#include<iostream>
#include<queue>
#include<vector>
#define ll long long
 
using namespace std;
 
struct node {
    int cur;
    ll dist;
    int K;
};
 
struct cmp {
    bool operator()(node right, node left) {
        return left.dist < right.dist;
    }
};
 
int N, M, K;
ll visited[10001][21];
vector<pair<int, ll>> list[10001];
 
int main()
{
    priority_queue<node, vector<node>, cmp>pq;
    scanf("%d %d %d"&N, &M, &K);
 
    for (int i = 2; i <= N; i++) {
        for (int j = 0; j <= K; j++) {
            visited[i][j] = 9222222222222222222;
        }
    }
 
    for (int i = 0; i < M; i++) {
        int u, v;
        ll c;
        scanf("%d %d %lld"&u, &v, &c);
        list[u].push_back({ v,c });
        list[v].push_back({ u,c });
    }
 
    pq.push({ 1,0,0 });
 
    while (!pq.empty()) {
        const int cur = pq.top().cur;
        const ll dist = pq.top().dist;
        const int cnt = pq.top().K;
        pq.pop();
 
        if (visited[cur][cnt] < dist) continue;
 
        if (cur == N) {
            printf("%lld", dist);
            return 0;
        }
 
        for (auto& next : list[cur]) {
            const int nextNode = next.first;
            const ll nextDist = next.second;
            if (cnt < K) {
                if (visited[nextNode][cnt + 1> dist) {
                    visited[nextNode][cnt + 1= dist;
                    pq.push({ nextNode,dist,cnt + 1 });
                }
            }
            
            if (visited[nextNode][cnt] > dist + nextDist) {
                visited[nextNode][cnt] = dist + nextDist;
                pq.push({ nextNode,dist + nextDist,cnt });
            }
        }
    }
}
cs
반응형

+ Recent posts