제출 #485260

#제출 시각아이디문제언어결과실행 시간메모리
485260arujbansalRobot (JOI21_ho_t4)C++17
100 / 100
968 ms83776 KiB
#include <bits/stdc++.h> using namespace std; using ll = long long; const int MXN = 1e5 + 1, MXM = 2e5 + 1; const ll INF = 1e18 + 5; struct state { int node, colour; ll cur_dist; state(int _node = 0, int _colour = 0, ll _cur_dist = 0) : node(_node), colour(_colour), cur_dist(_cur_dist) {} bool operator<(const state &other) const { return cur_dist > other.cur_dist; } }; signed main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int N, M; cin >> N >> M; map<int, ll> sum[N]; vector<array<int, 3>> g[N]; map<int, vector<pair<int, int>>> edges[N]; for (int i = 0; i < M; i++) { int a, b, c, p; cin >> a >> b >> c >> p; a--, b--; // {v, colour of edge, cost of deleting edge} g[a].emplace_back(array<int, 3>{b, c, p}); g[b].emplace_back(array<int, 3>{a, c, p}); // Sum of costs of all edges incident to a node with a particular colour sum[a][c] += p; sum[b][c] += p; // All edges incident to a node with a particular colour edges[a][c].emplace_back(b, p); edges[b][c].emplace_back(a, p); } vector<ll> dist(N, INF); dist[0] = 0; map<int, ll> dist_col[N]; priority_queue<state> pq; pq.emplace(0, -1, 0); // -1 represents free will, no colour restriction while (!pq.empty()) { auto [u, colour, cur_dist] = pq.top(); pq.pop(); if (colour == -1) { if (dist[u] != cur_dist) continue; for (const auto &[v, edge_col, edge_cost] : g[u]) { // 2.1 and 2.2 ll cost1 = min(cur_dist + sum[u][edge_col] - edge_cost, cur_dist + edge_cost); if (cost1 < dist[v]) { dist[v] = cost1; pq.emplace(v, -1, dist[v]); } // 2.3 if (!dist_col[v].count(edge_col) || cur_dist < dist_col[v][edge_col]) { dist_col[v][edge_col] = cur_dist; pq.emplace(v, edge_col, cur_dist); } } } else { if (cur_dist != dist_col[u][colour]) continue; for (const auto &[v, edge_cost] : edges[u][colour]) { ll cost = cur_dist + sum[u][colour] - edge_cost; if (cost < dist[v]) { dist[v] = cost; pq.emplace(v, -1, cost); } } } } cout << (dist[N - 1] < INF ? dist[N - 1] : -1); } /* Observations: 1. Always possible to change the colour of an edge so that it is different from all other edges connecting u if the answer is not -1 (?) 2. Three cases if current edge E(u, v) is of colour C: 2.1: We use E by changing colours of all other edges with C to go to v. At v, it's okay to use an edge of colour C since it gives us a worse cost than 2.2. 2.2: We change E's colour and go to v. Don't change the colour of any other edge incident to u with colour C. We can use an edge of any colour from v. This gives us a worse cost if we use an edge of colour C form v because we double count the cost for this edge. Case 2.3 handles this. 2.3: We change E's colour and use an edge of colour C from v. */
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...