Submission #340004

#TimeUsernameProblemLanguageResultExecution timeMemory
340004penguinhackerFactories (JOI14_factories)C++14
100 / 100
6049 ms335416 KiB
#include <bits/stdc++.h> #include "factories.h" using namespace std; #define ll long long #define ar array const int mxN = 500000; int n, sz[mxN]; ll best[mxN]; bool dead[mxN]; vector<pair<int, int>> adj[mxN]; vector<pair<int, ll>> par[mxN]; int dfs_sz(int u, int p) { sz[u] = 1; for (pair<int, int>& v : adj[u]) if (v.first != p && !dead[v.first]) sz[u] += dfs_sz(v.first, u); return sz[u]; } int get_centroid(int u, int p, int tsz) { for (pair<int, int>& v : adj[u]) if (v.first != p && !dead[v.first] && 2 * sz[v.first] > tsz) return get_centroid(v.first, u, tsz); return u; } void dfs(int u, int p, int c, ll d) { par[u].emplace_back(c, d); for (pair<int, int>& v : adj[u]) if (v.first != p && !dead[v.first]) dfs(v.first, u, c, d + v.second); } void centroid(int u = 0) { u = get_centroid(u, -1, dfs_sz(u, -1)); dfs(u, -1, u, 0); dead[u] = 1; for (pair<int, int> v : adj[u]) if (!dead[v.first]) centroid(v.first); dead[u] = 0; } void Init(int N, int A[], int B[], int D[]) { n = N; for (int i = 0; i < n - 1; ++i) { int a = A[i], b = B[i], d = D[i]; adj[a].emplace_back(b, d); adj[b].emplace_back(a, d); } centroid(); fill(best, best + n, 1e18); } ll Query(int S, int X[], int T, int Y[]) { vector<int> rb; // rollback best array for (int i = 0; i < S; ++i) { int u = X[i]; for (pair<int, ll> p : par[u]) { best[p.first] = min(best[p.first], p.second); rb.push_back(p.first); } } ll ans = 1e18; for (int i = 0; i < T; ++i) { int u = Y[i]; for (pair<int, ll> p : par[u]) ans = min(ans, best[p.first] + p.second); } for (int i : rb) best[i] = 1e18; assert(ans < (ll)1e18); return ans; } /*int main() { ios::sync_with_stdio(0); cin.tie(0); int n, q; cin >> n >> q; int a[n - 1], b[n - 1], d[n - 1]; for (int i = 0; i < n - 1; ++i) cin >> a[i] >> b[i] >> d[i]; Init(n, a, b, d); for (int i = 0; i < q; ++i) { int s, t; cin >> s >> t; int x[s], y[t]; for (int j = 0; j < s; ++j) cin >> x[j]; for (int j = 0; j < t; ++j) cin >> y[j]; cout << Query(s, x, t, y) << "\n"; } return 0; } */
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...