# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
397290 | JerryLiu06 | Factories (JOI14_factories) | C++11 | 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>
using namespace std;
using ll = long long;
using db = long double;
using str = string;
using pi = pair<int, int>;
using pl = pair<ll, ll>;
using pd = pair<db, db>;
using vi = vector<int>;
using vb = vector<bool>;
using vl = vector<ll>;
using vd = vector<db>;
using vs = vector<str>;
using vpi = vector<pi>;
using vpl = vector<pl>;
using vpd = vector<pd>;
#define mp make_pair
#define f first
#define s second
#define bg(x) begin(x)
#define all(x) bg(x), end(x)
#define sor(x) sort(all(x))
#define ft front()
#define bk back()
#define pb push_back
#define pf push_front
#define lb lower_bound
#define ub upper_bound
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define F0R(i, a) FOR(i, 0, a)
#define ROF(i, a, b) for (int i = (b) - 1; i >= (a); i--)
#define R0F(i, a) ROF(i, 0, a)
#define EACH(a, x) for (auto& a : x)
const int MOD = 1e9 + 7;
const int MX = 5e5 + 10;
const ll INF = 1e18;
int N; vpi adj[MX]; int sub[MX], num[MX], par[MX]; ll dist[MX][20], ans[MX]; bool vis[MX];
void DFS1(int X, int P) {
sub[X] = 1; EACH(Y, adj[X]) if (Y.f != P && !vis[Y.f]) { DFS1(Y.f, X); sub[X] += sub[Y.f]; }
}
int centroid(int X, int P, int S) {
EACH(Y, adj[X]) if (Y.f != P && !vis[Y.f] && sub[Y.f] > S / 2) return centroid(Y.f, X, S); return X;
}
void DFS2(int X, int P, ll D) {
dist[X][num[X]++] = D; EACH(Y, adj[X]) if (Y.f != P && !vis[Y.f]) DFS2(Y.f, X, D + Y.s);
}
void decomp(int X, int P) {
DFS1(X, 0); int C = centroid(X, 0, sub[X]); vis[C] = true; par[C] = P;
DFS2(C, P, 0); EACH(Y, adj[C]) if (!vis[Y.f]) decomp(Y.f, C);
}
void update(int X, int T) {
int Y = X; int ind = num[X] - 1;
while (Y != 0) { if (T == 1) ans[Y] = min(ans[Y], dist[X][ind]); else ans[Y] = INF; Y = par[Y]; ind--; }
}
ll query(int X) {
int Y = X; int ind = num[X] - 1; ll res = INF;
while (Y != 0) { res = min(res, ans[Y] + dist[X][ind]); Y = par[Y]; ind--; } return res;
}
void init(int _N, int A[], int B[], int D[]) {
N = _N; F0R(i, N - 1) { A[i]++, B[i]++; adj[A[i]].pb({B[i], D[i]}), adj[B[i]].pb({A[i], D[i]}); }
decomp(1, 0); FOR(i, 1, N) ans[i] = INF;
}
ll Query(int S, int X[], int T, int Y[]) {
ll res = INF; F0R(i, S) update(++X[i], 1);
F0R(i, T) res = min(res, query(++Y[i])); F0R(i, S) update(X[i], 0); return res;
}