Submission #667936

#TimeUsernameProblemLanguageResultExecution timeMemory
667936stevancvElection Campaign (JOI15_election_campaign)C++14
100 / 100
177 ms32856 KiB
#include <bits/stdc++.h> #define ll long long #define ld long double #define sp ' ' #define en '\n' #define smin(a, b) a = min(a, b) #define smax(a, b) a = max(a, b) using namespace std; const int N = 1e5 + 2; const int inf = 2e9; vector<int> g[N]; int par[N][17], in[N], out[N], tsz; void Dfs(int s, int e) { in[s] = ++tsz; par[s][0] = e; for (int i = 1; i < 17; i++) par[s][i] = par[par[s][i - 1]][i - 1]; for (int u : g[s]) { if (u != e) Dfs(u, s); } out[s] = ++tsz; } bool Ancestor(int u, int v) { return in[u] <= in[v] && out[v] <= out[u]; } int Lca(int u, int v) { if (Ancestor(u, v)) return u; if (Ancestor(v, u)) return v; for (int i = 16; i >= 0; i--) { if (par[u][i] && !Ancestor(par[u][i], v)) u = par[u][i]; } return par[u][0]; } ll dp[N], sum[N]; vector<array<int, 3>> paths[N]; struct fenwick { ll bit[2 * N]; void Add(int x, ll v) { for (; x < 2 * N; x += x & (-x)) bit[x] += v; } ll P(int x) { ll ans = 0; for (; x > 0; x -= x & (-x)) ans += bit[x]; return ans; } ll Get(int l, int r) { if (l > r) return 0; return P(r) - P(l - 1); } }f1, f2; void Dfs1(int s, int e) { for (int u : g[s]) { if (u == e) continue; Dfs1(u, s); sum[s] += dp[u]; } dp[s] = sum[s]; f1.Add(in[s], sum[s]); f1.Add(out[s], -sum[s]); for (auto u : paths[s]) { int a = u[0]; int b = u[1]; int c = u[2]; smax(dp[s], f1.Get(in[s], in[a]) + f1.Get(in[s] + 1, in[b]) - f2.Get(in[s] + 1, in[a]) - f2.Get(in[s] + 1, in[b]) + c); } f2.Add(in[s], dp[s]); f2.Add(out[s], -dp[s]); } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; cin >> n; for (int i = 0; i < n - 1; i++) { int u, v; cin >> u >> v; g[u].push_back(v); g[v].push_back(u); } Dfs(1, 0); int m; cin >> m; for (int i = 0; i < m; i++) { int a, b, c; cin >> a >> b >> c; paths[Lca(a, b)].push_back({a, b, c}); } Dfs1(1, 0); cout << dp[1] << en; return 0; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...