BOJ2176: 합리적인 이동경로

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

  • 다익스트라로 각 노드 별 최단거리를 구한 뒤에, DP를 돌리면 된다.
  • C++17으로 구현하면 다익스트라도 깔끔해진다.
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
#include <bits/stdc++.h>
using namespace std;

struct Edge {
  int v, c;
};

struct Node {
  int u, d;
  bool operator<(const Node &b) const {
    return d > b.d;
  }
};

class Tree {
  const unsigned int INF = 2147483648;
  int N;
  vector<unsigned int> dist, dp;
  vector<vector<Edge>> adj;
public:
  Tree(int n): N(n), dist(n+1, INF), dp(n+1, INF), adj(n+1) {}
  void addEdge(int u, int v, int c);
  void dijkstra();
  unsigned int go(int u);
};

void Tree::addEdge(int u, int v, int c) {
  adj[u].push_back({v, c});
  adj[v].push_back({u, c});
}

void Tree::dijkstra() {
  priority_queue<Node> pq;
  pq.push({2, 0});
  dist[2] = 0;
  while(pq.size()) {
    auto [u, d] = pq.top();
    pq.pop();
    if (d > dist[u])
      continue;

    for(auto [v, c] : adj[u]) {
      if (c + d < dist[v]) {
        pq.push({v, c+d});
        dist[v] = c+d;
      }
    }
  }
}

unsigned int Tree::go(int u) {
  if(u == 2) return 1;
  if(dp[u] != INF) return dp[u];
  int ans = 0;
  for(auto [v, c] : adj[u])
    if(dist[u] > dist[v])
      ans += go(v);
  return dp[u] = ans;
}

int main() {
  ios::sync_with_stdio(false);
  int N, M, u, v, c;
  cin >> N >> M;
  Tree tree(N);
  for(int i = 0; i < M; i++) {
    cin >> u >> v >> c;
    tree.addEdge(u, v, c);
  }
  tree.dijkstra();
  cout << tree.go(1);
}