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;
int par[100005][20], sum[100005][20], depth[100005], dp1[100005], dp2[100005];
vector<pair<pair<int, int>, int> > vec[100005];
vector<pair<int, int> > upd[100005];
vector<int> adj[100005];
int lca(int u, int v)
{
if (depth[u]<depth[v])
swap(u, v);
int d=depth[u]-depth[v];
for (int i=19; i>=0; i--)
if (d&(1<<i))
u=par[u][i];
if (u==v)
return u;
for (int i=19; i>=0; i--)
{
if (par[u][i]!=par[v][i])
{
u=par[u][i];
v=par[v][i];
}
}
return par[u][0];
}
int calc(int u, int d)
{
int res=0;
for (int i=19; i>=0; i--)
{
if (d&(1<<i))
{
res+=sum[u][i];
u=par[u][i];
}
}
return res;
}
void dfs1(int u, int p)
{
par[u][0]=p;
for (int i=1; i<20; i++)
{
par[u][i]=par[par[u][i-1]][i-1];
if (depth[u]-depth[par[u][i]]==(1<<i))
upd[par[u][i]].push_back({u, i});
}
for (int v:adj[u])
{
if (v==p)
continue;
depth[v]=depth[u]+1;
dfs1(v, u);
}
}
void dfs2(int u)
{
for (int v:adj[u])
{
if (v==par[u][0])
continue;
dfs2(v);
dp2[u]+=dp1[v];
}
for (int i=0; i<upd[u].size(); i++)
{
int v=upd[u][i].first, x=upd[u][i].second;
sum[v][x]=sum[v][x-1]+sum[par[v][x-1]][x-1];
}
dp1[u]=dp2[u];
for (int i=0; i<vec[u].size(); i++)
{
int a=vec[u][i].first.first, b=vec[u][i].first.second, c=vec[u][i].second;
dp1[u]=max(dp1[u], dp2[u]+c-calc(a, depth[a]-depth[u])-calc(b, depth[b]-depth[u]));
}
sum[u][0]=dp1[u]-dp2[u];
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n;
for (int i=1; i<n; i++)
{
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs1(1, 1);
cin >> m;
for (int i=1; i<=m; i++)
{
int a, b, c;
cin >> a >> b >> c;
vec[lca(a, b)].push_back({{a, b}, c});
}
dfs2(1);
cout << dp1[1];
}
Compilation message (stderr)
election_campaign.cpp: In function 'void dfs2(int)':
election_campaign.cpp:66:20: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<std::pair<int, int> >::size_type' {aka 'long unsigned int'} [-Wsign-compare]
66 | for (int i=0; i<upd[u].size(); i++)
| ~^~~~~~~~~~~~~~
election_campaign.cpp:72:20: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<std::pair<std::pair<int, int>, int> >::size_type' {aka 'long unsigned int'} [-Wsign-compare]
72 | for (int i=0; i<vec[u].size(); i++)
| ~^~~~~~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |