From c9e7144426588c2a77d122b1506c9c1c97efa900 Mon Sep 17 00:00:00 2001 From: Eat-Swap Date: Sat, 14 May 2022 21:41:24 +0800 Subject: [PATCH] add: 220514 [cpp] --- cpp/2205/220514.cpp | 59 +++++++++++++++++++++++++++++++++++++++++ cpp/2205/CMakeLists.txt | 2 +- 2 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 cpp/2205/220514.cpp diff --git a/cpp/2205/220514.cpp b/cpp/2205/220514.cpp new file mode 100644 index 0000000..cfdbd26 --- /dev/null +++ b/cpp/2205/220514.cpp @@ -0,0 +1,59 @@ +#include +#include +#include +#include + +/** + * 743. Network Delay Time + * You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target. + * We will send a signal from a given node k. Return the time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1. + * + * Comment: This is Dijkstra's algorithm. + */ + +class Solution { +public: + static int networkDelayTime(const std::vector>& times, int n, int k) { + const int edgeCnt = times.size(); + std::vector> edges; + std::vector> G(n); + edges.reserve(edgeCnt); + for (int i = 0; i < edgeCnt; ++i) { + edges.emplace_back(times[i][0] - 1, times[i][1] - 1, times[i][2]); + G[times[i][0] - 1].push_back(i); + } + + std::vector dist(n, 0x6FFFFFFF); + std::vector vis(n); + --k; + + // pair + std::priority_queue, std::vector>, std::greater<>> q; + q.push({0, k}); + dist[k] = 0; + while (!q.empty()) { + const auto [len, node] = q.top(); + q.pop(); + + if (vis[node]) + continue; + vis[node] = true; + + for (int eId : G[node]) { + const auto [f, t, d] = edges[eId]; + if (dist[t] <= dist[node] + d) + continue; + dist[t] = dist[node] + d; + q.push({dist[t], t}); + } + } + + int ret = *std::max_element(dist.begin(), dist.end()); + return ret == 0x6FFFFFFF ? -1 : ret; + } +}; + +int main() { + std::cout << Solution::networkDelayTime({{2,1,1},{2,3,1},{3,4,1}}, 4, 2); + return 0; +} diff --git a/cpp/2205/CMakeLists.txt b/cpp/2205/CMakeLists.txt index ccbd348..bae3437 100644 --- a/cpp/2205/CMakeLists.txt +++ b/cpp/2205/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2205) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2205 220514-CN.cpp) +ADD_EXECUTABLE(2205 220514.cpp)