Submission #398151

#TimeUsernameProblemLanguageResultExecution timeMemory
398151bonopoFactories (JOI14_factories)C++14
100 / 100
4398 ms303576 KiB
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> using namespace std; using namespace __gnu_pbds; #define pb push_back #define el "\n" #define f first #define s second #pragma GCC optimize("O3") #pragma GCC target("sse4") typedef long long ll; const ll MM=5e5+5, MOD=1e9+7, LOG=20, INF=1e18; int dep[MM], sz[MM], nxt[MM], in[MM], ot[MM], head[2*MM], ct=1, chn; ll dst[MM], spc[MM], pcl[LOG][MM]; pair<int,int> st[LOG][4*MM]; bool blk[MM]; struct E {int nxt; pair<int,int> v; } e[2*MM]; void add(int u, int v, int w){ e[chn].v={v,w}; e[chn].nxt=head[u]; head[u]=chn++; } int lg2(int x) { return 32-__builtin_clz(x)-1; } void df1(int u, int pa) { dep[u]=dep[pa]+1; st[0][ct]=make_pair(dep[u], u); in[u]=ct++; for(int i=head[u]; i!=-1; i=e[i].nxt) { int v=e[i].v.f, w=e[i].v.s; if(v==pa) continue; dst[v]=dst[u]+w; df1(v, u); sz[u]+=sz[v]; st[0][ct++]=make_pair(dep[u], u); } ot[u]=ct; } inline int qry(int l, int r) { int lg=lg2(r-l+1); return min(st[lg][l], st[lg][r-(1<<lg)+1]).s; } inline int lca(int u, int v) { if(in[u]>in[v]) return qry(in[v], in[u]); return qry(in[u], in[v]); } void gsz(int u, int pa) { sz[u]=1; for(int i=head[u]; i!=-1; i=e[i].nxt) { int v=e[i].v.f; if(blk[v]||v==pa) continue; gsz(v, u); sz[u]+=sz[v]; } } int ctr(int u, int pa, int nd) { for(int i=head[u]; i!=-1; i=e[i].nxt) { int v=e[i].v.f; if(blk[v]||v==pa) continue; if(sz[v]*2>nd) return ctr(v, u, nd); } return u; } inline ll dist(int u, int c, int id) { if(pcl[id][u]) return pcl[id][u]; return pcl[id][u]=dst[u]+dst[c]-2LL*dst[lca(u, c)]; } void slv(int u, int pa) { gsz(u, -1); u=ctr(u, -1, sz[u]); blk[u]=1; nxt[u]=pa; for(int i=head[u]; i!=-1; i=e[i].nxt) { int v=e[i].v.f; if(!blk[v]) slv(v, u); } } void Init(int N, int A[], int B[], int D[]) { memset(head, -1, sizeof(head)); for(int i=0; i<N; ++i) spc[i]=INF; for(int i=0; i<N-1; ++i) { add(A[i], B[i], D[i]); add(B[i], A[i], D[i]); } df1(0, 0); slv(0, -1); for(int i=1; i<LOG; ++i) for(int j=1; j+(1<<i)-1<=ct; ++j) st[i][j]=min(st[i-1][j], st[i-1][j+(1<<(i-1))]); } long long Query(int S, int X[], int T, int Y[]) { for(int i=0, c, l=0; i<S; ++i, l=0) { c=X[i]; while(c!=-1) spc[c]=min(spc[c], dist(X[i], c, l)), c=nxt[c], ++l; } long long ans=INF; for(int i=0, c, l=0; i<T; ++i, l=0) { c=Y[i]; while(c!=-1) ans=min(ans, dist(Y[i], c, l)+spc[c]), c=nxt[c], ++l; } for(int i=0, c; i<S; ++i) { c=X[i]; while(c!=-1) spc[c]=INF, c=nxt[c]; } return ans; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...