기술 블로그

10217번 KCM Travel 본문

알고리즘 문제/BOJ

10217번 KCM Travel

parkit 2020. 1. 5. 00:43
728x90
반응형

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



나는 처음에 기존 money[Max]라는 배열을 통해


money 배열도 dist 배열(처음에는 1차원 배열)처럼 똑같이 다익스트라로 활용하였다.


그러나 계속 안 풀려서 결국 아이디어를 얻었다.



아이디어는 기존 다익스트라에서 한 차원 더 늘리는 것이었다.


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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <bits/stdc++.h>
 
using namespace std;
 
#define Max 111
#define INF 987654321
 
typedef struct info
{
    int next, money, distance;
}info;
 
int n, m, k, dist[Max][10001];
vector<info> v[Max];
 
int dijstra(int start)
{
    for (int i = 0; i < Max; i++) {
        fill(dist[i], dist[i] + 10001, INF); // dist[i] + Max라고 했었다.
    }
 
    dist[start][0= 0;
 
    priority_queue<pair<pair<intint>int > > pq;
    pq.push({ {0, start}, 0 });
 
    while (!pq.empty())
    {
        int here = pq.top().first.second;
        int distance = -pq.top().first.first;
        int cost = pq.top().second;
 
        pq.pop();
 
        if (dist[here][cost] < distance) continue;
 
        for (auto i : v[here]) {
            int next = i.next;
            int next_cost = i.money;
            int next_distance = i.distance;
 
            // 문제 조건
            if (cost + next_cost > m) continue;
 
            int sum = cost + next_cost;
 
            // dist[here][cost] 말고, distance라고 써도 된다.
            if (dist[next][sum] > dist[here][cost] + next_distance) {            
                dist[next][sum] = dist[here][cost] + next_distance;
                pq.push({ {-dist[next][sum], next}, sum });
            }
        }
    }
 
    int ret = -1;
 
    // m 이하까지 비용 사용 가능
    for (int i = 0; i <= m; i++) {
        if (dist[n][i] != INF) {
            ret = min(ret, dist[n][i]);
        }
    }
 
    return ret;
}
 
int main()
{
    //freopen("C:\\Users\\park7\\Desktop\\sample_input.txt", "r", stdin);
    cin.tie(0);
 
    int T = 0;
    scanf("%d"&T);
 
    while (T--)
    {
        int u, vc, c, d;
 
        for (int i = 0; i < Max; i++) {
            v[i].clear();
        }
 
        scanf("%d %d %d"&n, &m, &k);
 
        for (int i = 0; i < k; i++) {
            scanf("%d %d %d %d"&u, &vc, &c, &d);
            v[u].push_back({ vc, c, d });
        }
 
        int g = dijstra(1);
 
        if (g == -1printf("Poor KCM\n");
        else printf("%d\n", g);
    }
 
    return 0;
}
cs


















728x90
반응형

'알고리즘 문제 > BOJ' 카테고리의 다른 글

괄호 추가하기 시리즈  (0) 2020.01.06
2638번 치즈  (0) 2020.01.06
2352번 반도체 설계  (0) 2020.01.04
17267번 상남자  (0) 2020.01.03
1058번 친구  (0) 2020.01.03