Submission #264535

#TimeUsernameProblemLanguageResultExecution timeMemory
264535AtalasionElection Campaign (JOI15_election_campaign)C++14
100 / 100
481 ms54008 KiB
//khodaya khodet komak kon #include <bits/stdc++.h> #define F first #define S second #define pb push_back #define all(x) x.begin(), x.end() #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math") #define int long long using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; const int N = 300000 + 10; const ll MOD = 1000000000 + 7; const ll INF = 1000000010; const ll LOG = 19; int par[N][LOG], n, q, A[N], B[N], C[N], h[N], st[N], ft[N], Time, fen[N], dp[N]; vi G[N], Q[N]; inline void add(int id, int x){ for (; id < N; id += (id & (-id))) fen[id] += x; } inline int get(int id){ int res = 0; for (; id > 0; id -= (id & (-id))) res += fen[id]; return res; } void DFS(int v = 1, int p = 0){ st[v] = ++Time; par[v][0] = p; for (int i = 1; i < LOG; i++) par[v][i] = par[par[v][i - 1]][i - 1]; for (auto u:G[v]){ if (u == p)continue; h[u] = h[v] + 1; DFS(u, v); } ft[v] = Time + 1; } int getpar(int v, int k){ for (int i = 0; i < LOG; i++){ if (k & (1 << i)) v = par[v][i]; } return v; } int LCA(int v, int u){ if (h[v] < h[u]) swap(v, u); v = getpar(v, h[v] - h[u]); if (v == u) return v; for (int i = LOG - 1; i >= 0; i--){ if (par[v][i] != par[u][i]) v = par[v][i], u = par[u][i]; } return par[v][0]; } void DFS2(int v = 1, int p = 0){ int sm = 0; for (auto u:G[v]){ if (u == p) continue; DFS2(u, v); sm += dp[u]; } dp[v] = sm; for (auto u:Q[v]){ int lca = LCA(A[u], B[u]); if (h[A[u]] < h[B[u]]) swap(A[u], B[u]); if (lca == B[u]){ int vv = getpar(A[u], h[A[u]] - h[v] - 1); dp[v] = max(dp[v], C[u] + sm - dp[vv] + get(st[A[u]])); }else{ int vv = getpar(A[u], h[A[u]] - h[v] - 1), uu = getpar(B[u], h[B[u]] - h[v] - 1); dp[v] = max(dp[v], C[u] + sm - dp[uu] - dp[vv] + get(st[A[u]]) + get(st[B[u]])); } } add(st[v], sm); add(st[v] + 1, -sm); for (auto u:G[v]){ if (u == p) continue; add(st[u], sm - dp[u]); add(ft[u], -(sm - dp[u])); } } int32_t main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; for (int i = 0; i < n - 1; i++){ int v, u; cin >> v >> u; G[v].pb(u), G[u].pb(v); } DFS(); cin >> q; for (int i = 1; i <= q; i++){ cin >> A[i] >> B[i] >> C[i]; //cout << LCA(A[i], B[i]) << '\n'; Q[LCA(A[i], B[i])].pb(i); } DFS2(); cout << dp[1]; 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...