제출 #287374

#제출 시각아이디문제언어결과실행 시간메모리
287374BertedEvacuation plan (IZhO18_plan)C++14
100 / 100
766 ms46956 KiB
#include <iostream> #include <queue> #include <vector> #include <algorithm> #include <assert.h> #define pii pair<int, int> #define vi vector<int> #define vpi vector<pii> #define fst first #define snd second using namespace std; const int INF = 1e9, LG = 17; int n, m, k, q; vpi adj[100001]; vi tree[100001]; int dist[100001], par[100001], h[100001], sps[100001][LG][2]; vpi ord; priority_queue<pii, vector<pii>, greater<pii>> pq; void runDijkstra() { while (pq.size()) { int u = pq.top().snd, d = pq.top().fst; pq.pop(); //cout << "DIST : " << u << " " << dist[u] << "\n"; if (dist[u] == d) { for (auto v : adj[u]) { if (dist[u] + v.snd < dist[v.fst]) { dist[v.fst] = dist[u] + v.snd; pq.push({dist[v.fst], v.fst}); } } } } } int fn(int x) {return par[x] = (par[x] == x) ? x : fn(par[x]);} void jn(int a, int b) { int oa = fn(a), ob = fn(b); if (oa != ob) { par[ob] = oa; tree[a].push_back(b); tree[b].push_back(a); } } void DFS(int u, int p, int val) { sps[u][0][0] = p; sps[u][0][1] = val; h[u] = (p == -1) ? 0 : (h[p] + 1); for (int i = 1; i < LG; i++) { if (sps[u][i - 1][0] != -1) { sps[u][i][0] = sps[sps[u][i - 1][0]][i - 1][0]; sps[u][i][1] = min(sps[u][i - 1][1], sps[sps[u][i - 1][0]][i - 1][1]); } else {sps[u][i][0] = -1; sps[u][i][1] = INF;} } for (auto v : tree[u]) { if (v != p) {DFS(v, u, dist[u]);} } } int getAnswer(int u, int v) { int res = min(dist[u], dist[v]); if (h[u] > h[v]) {swap(v, u);} for (int i = 0; h[v] - h[u]; i++) { if ((h[v] - h[u]) & (1 << i)) { res = min(sps[v][i][1], res); v = sps[v][i][0]; } } for (int i = LG - 1; i >= 0; i--) { if (sps[u][i][0] != sps[v][i][0]) { res = min(res, min(sps[u][i][1], sps[v][i][1])); u = sps[u][i][0]; v = sps[v][i][0]; } } if (u != v) { res = min(res, min(sps[u][0][1], sps[v][0][1])); u = sps[u][0][0]; v = sps[v][0][0]; } //assert(u == v); return res; } int main() { ios :: sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> m; for (int i = 0; i < n; i++) {dist[i] = INF; par[i] = -1;} for (int i = 0; i < m; i++) { int u, v, w; cin >> u >> v >> w; adj[u - 1].push_back({v - 1, w}); adj[v - 1].push_back({u - 1, w}); } cin >> k; for (int i = 0; i < k; i++) { int x; cin >> x; x--; dist[x] = 0; pq.push({0, x}); } runDijkstra(); for (int i = 0; i < n; i++) {ord.push_back({-dist[i], i});} sort(ord.begin(), ord.end()); for (int i = 0; i < n; i++) { int u = ord[i].snd; par[u] = u; for (auto v : adj[u]) { if (par[v.fst] != -1) {jn(v.fst, u);} } } DFS(0, -1, INF); cin >> q; for (int i = 0; i < q; i++) { int u, v; cin >> u >> v; cout << getAnswer(u - 1, v - 1) << "\n"; } return 0; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...