# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
673975 | Cookie | Factories (JOI14_factories) | C++14 | 0 ms | 0 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
#include<fstream>
//#include "factories.h"
using namespace std;
ifstream fin("INTERNET.INP");
ofstream fout("INTERNET.OUT");
#define ll long long
#define vt vector
#define pb push_back
#define fi first
#define se second
#define forr(i, a, b) for(int i = a; i < b; i++)
#define dorr(i, a, b) for(int i = a; i >= b; i--)
#define pii pair<int, int>
#define pll pair<ll, ll>
const int mxn = 5e5, sq = 300, mxv = 1e4;
int n;
vt<pll>adj[mxn + 1];
ll sz[mxn + 1], par[mxn + 1], ans[mxn + 1];
vt<int>s, t;
map<int, ll>dis[mxn + 1];
bool vis[mxn + 1];
int dfs(int s, int pre){
sz[s] = 1;
for(auto [i, w]: adj[s]){
if(i != pre && !vis[i]){
sz[s] += dfs(i, s);
}
}
return(sz[s]);
}
int centroid(int s, int pre, int need){
for(auto [i, w]: adj[s]){
if(i != pre && !vis[i]){
if(sz[i] * 2 > need)return(centroid(i, s, need));
}
}
return(s);
}
void dfs2(int s, int c, int pre, ll d){
dis[c][s] = d;
for(auto [i, w]: adj[s]){
if(i != pre && !vis[i]){
dfs2(i, c, s, d + w);
}
}
}
void build(int s, int pre){
int c = centroid(s, -1, dfs(s, -1));
vis[c] = true; par[c] = pre;
dis[c][c] = 0;
for(auto [i, w]: adj[c]){
if(i != pre && !vis[i]){
dfs2(i, c, c, w);
}
}
for(auto [i, w]: adj[c]){
if(!vis[i]){
build(i, c);
}
}
}
void Init(int N, int A[], int B[], int D[]) {
n = N;
for(int i = 0; i < n - 1; i++){
adj[A[i]].pb({B[i], D[i]}); adj[B[i]].pb({A[i], D[i]});
}
build(0, -1); //centroid decompsoing the tree
for(int i = 0; i < n; i++)ans[i] = 1e18;
}
void add(int x){
for(int i = x; i != -1; i = par[i])ans[i] = min(ans[i], dis[i][x]);
}
void rem(int x){
for(int i = x; i != -1; i = par[i])ans[i] = 1e18;
}
ll see(int x){
ll res = 1e18; int cnt = 0;
for(int i = x; i != -1; i = par[i]){
cnt++; res = min(res, ans[i] + dist[i][x]);
}
assert(cnt <= 100);
return(res);
}
ll solve(){
for(int i = 0; i < s.size(); i++)add(s[i]);
ll res = 1e18;
for(int i = 0; i < t.size(); i++)res = min(see(t[i]), res);
for(int i = 0; i < s.size(); i++)rem(s[i]);
return(res);
}
long long Query(int S, int X[], int T, int Y[]) {
s.clear(); t.clear();
for(int i = 0; i < S; i++)s.pb(X[i]);
for(int i = 0; i < T; i++)t.pb(Y[i]);
return(solve());
}