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;
const int nx=2e5+5, kx=18;
long long n, u, v, c[nx], c2[nx], dp[nx], cnt[nx], res, pa[nx][kx], lvl[nx];
vector<pair<int, int>> d[nx];
void dfs(int u, int p)
{
lvl[u]=lvl[p]+1; pa[u][0]=p;
for (int i=1; i<kx; i++) pa[u][i]=pa[pa[u][i-1]][i-1];
for (auto [v, idx]:d[u]) if (v!=p) dfs(v, u);
}
int lca(int u, int v)
{
if (lvl[u]>lvl[v]) swap(u, v);
for (int i=kx-1; i>=0; i--) if (lvl[pa[v][i]]>=lvl[u]) v=pa[v][i];
if (u==v) return v;
for (int i=kx-1; i>=0; i--) if (pa[u][i]!=pa[v][i]) u=pa[u][i], v=pa[v][i];
return pa[u][0];
}
void dfs2(int u, int p, int idx)
{
for (auto [v, id]:d[u]) if (v!=p) dfs2(v, u, id), dp[u]+=dp[v];
cnt[idx]=dp[u];
}
int main()
{
cin.tie(NULL)->sync_with_stdio(false);
cin>>n;
for (int i=1; i<n; i++) cin>>u>>v>>c[i]>>c2[i], d[u].push_back({v, i}), d[v].push_back({u, i});
dfs(1, 1);
for (int i=2; i<=n; i++) dp[i]++, dp[i-1]++, dp[lca(i, i-1)]-=2;
dfs2(1, 1, 0);
for (int i=1; i<n; i++) res+=min(c[i]*cnt[i], c2[i]);
cout<<res;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |