Submission #79096

#TimeUsernameProblemLanguageResultExecution timeMemory
79096gs14004Factories (JOI14_factories)C++17
0 / 100
36 ms12408 KiB
#include "factories.h" #include <vector> #include <queue> #include <utility> #include <algorithm> using namespace std; typedef long long lint; typedef pair<lint,int> pi; vector<pi> graph[500005]; int piv, dfn[500005]; int dep[500005], sz[500005]; lint dist[500005]; int par[500005][19]; int dfs(int x, int p){ dfn[x] = ++piv; sz[x] = 1; for (auto &i : graph[x]){ if(p == i.second) continue; dep[i.second] = dep[x] + 1; dist[i.second] = dist[x] + i.first; par[i.second][0] = x; sz[x] += dfs(i.second, x); } return sz[x]; } void Init(int N, int A[], int B[], int D[]){ for (int i=0; i<N-1; i++) { graph[A[i]+1].push_back(pi(D[i],B[i]+1)); graph[B[i]+1].push_back(pi(D[i],A[i]+1)); } dfs(1, 0); for(int i=1; i<=18; i++){ for(int j=1; j<=N; j++){ par[j][i] = par[par[j][i-1]][i-1]; } } } int lca(int x, int y){ if(dep[x] < dep[y]) swap(x,y); int dx = dep[x] - dep[y]; for(int i=0; (1<<i)<=dx; i++){ if((dx >> i) & 1) x = par[i][x]; } for (int i=18; i>=0; i--) { if(par[i][x] != par[i][y]){ x = par[x][i]; y = par[y][i]; } } if(x != y) x = par[x][0]; return x; } bool cmp(int a, int b){ return dfn[a] < dfn[b]; } bool sub(int a, int b){ return dfn[a] + sz[a] >= dfn[b] + sz[b]; } vector<int> pos; int c; int object[500005]; lint D[500005]; void const_g(){ vector<int> stk; for(auto &i : pos){ if(stk.empty()) stk.push_back(i); else{ while(!stk.empty() && !sub(stk.back(), i)) stk.pop_back(); int par = stk.back(); int cur = i; graph[par].emplace_back(dist[cur] - dist[par], cur); graph[cur].emplace_back(dist[cur] - dist[par], par); stk.push_back(cur); } } } lint dijkstra(int n, int* s){ priority_queue<pi,vector<pi>,greater<pi> > pq; for (int i=0; i<n; i++) { pq.push(pi(0ll,s[i] + 1)); D[s[i] + 1] = 0; } while (!pq.empty()) { pi t = pq.top(); pq.pop(); if(D[t.second] != t.first) continue; if(object[t.second] == c) return t.first; for(auto &i : graph[t.second]){ if(D[i.second] > t.first + i.first){ D[i.second] = t.first + i.first; pq.push(pi(D[i.second], i.second)); } } } return -1; } lint Query(int S, int X[], int T, int Y[]){ c++; pos.clear(); for (int i=0; i<S; i++) { pos.push_back(X[i]+1); } for (int i=0; i<T; i++) { object[Y[i]+1] = c; pos.push_back(Y[i]+1); } sort(pos.begin(),pos.end(),cmp); int p = (int)pos.size() - 1; for (int i=0; i<p; i++) { pos.push_back(lca(pos[i],pos[i+1])); } sort(pos.begin(),pos.end(),cmp); pos.resize(unique(pos.begin(),pos.end()) - pos.begin()); for(auto &i : pos){ D[i] = 1e18; graph[i].clear(); } const_g(); lint ret = dijkstra(S,X); return ret; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...