#line 2 "/Users/tiramister/CompetitiveProgramming/Cpp/CppLibrary/tools/vector_alias.hpp" #include template std::vector vec(int len, T elem) { return std::vector(len, elem); } #line 2 "/Users/tiramister/CompetitiveProgramming/Cpp/CppLibrary/Graph/dijkstra.hpp" #line 2 "/Users/tiramister/CompetitiveProgramming/Cpp/CppLibrary/Tools/heap_alias.hpp" #include template using MaxHeap = std::priority_queue; template using MinHeap = std::priority_queue, std::greater>; #line 2 "/Users/tiramister/CompetitiveProgramming/Cpp/CppLibrary/Graph/graph.hpp" #line 4 "/Users/tiramister/CompetitiveProgramming/Cpp/CppLibrary/Graph/graph.hpp" template struct Edge { int src, dst; Cost cost; Edge() = default; Edge(int src, int dst, Cost cost = 1) : src(src), dst(dst), cost(cost){}; bool operator<(const Edge& e) const { return cost < e.cost; } bool operator>(const Edge& e) const { return cost > e.cost; } }; template struct Graph : public std::vector>> { using std::vector>>::vector; void span(bool direct, int src, int dst, Cost cost = 1) { (*this)[src].emplace_back(src, dst, cost); if (!direct) (*this)[dst].emplace_back(dst, src, cost); } }; #line 5 "/Users/tiramister/CompetitiveProgramming/Cpp/CppLibrary/Graph/dijkstra.hpp" template std::vector dijkstra(const Graph& graph, int s) { std::vector dist(graph.size(), -1); dist[s] = 0; MinHeap> que; que.emplace(0, s); while (!que.empty()) { auto [d, v] = que.top(); que.pop(); if (d > dist[v]) continue; for (const auto& e : graph[v]) { if (dist[e.dst] != -1 && dist[e.dst] <= dist[v] + e.cost) continue; dist[e.dst] = dist[v] + e.cost; que.emplace(dist[e.dst], e.dst); } } return dist; } #line 3 "main.cpp" #include #include #line 7 "main.cpp" const std::vector> dxys{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; using lint = long long; void solve() { int n, m; std::cin >> n >> m; auto xss = vec(n, vec(n, 0LL)); while (m--) { int u, v; std::cin >> u >> v; std::cin >> xss[--u][--v]; } auto enc = [&](int x, int y, int t) { return (x * n + y) * 2 + t; }; Graph graph(n * n * 2); for (int x = 0; x < n; ++x) { for (int y = 0; y < n; ++y) { for (auto [dx, dy] : dxys) { auto nx = x + dx, ny = y + dy; if (nx < 0 || n <= nx || ny < 0 || n <= ny) continue; for (int t = 0; t <= 1; ++t) { graph.span(true, enc(x, y, t), enc(nx, ny, t), xss[nx][ny] + 1); } graph.span(true, enc(x, y, 0), enc(nx, ny, 1), 1); } } } auto ds = dijkstra(graph, enc(0, 0, 0)); std::cout << ds[enc(n - 1, n - 1, 1)] << "\n"; } int main() { std::cin.tie(nullptr); std::ios::sync_with_stdio(false); solve(); return 0; }