This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
//Challenge: Accepted
#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
#include <set>
#define ll long long
#define maxn 200005
#define pii pair<int, ll>
#define ff first
#define ss second
#define mod 1000000007
#define io ios_base::sync_with_stdio(0);cin.tie(0);
using namespace std;
vector<pii> adj[maxn];
ll tup[maxn], up[maxn], best[maxn], bind[maxn];
multiset<ll> mdown[maxn];
void dfs(int n, int par) {
for (auto v:adj[n]) {
if (v.ff != par) {
dfs(v.ff, n);
tup[n] += tup[v.ff] + up[v.ff];
if (v.ss + best[v.ff] > best[n]) {
best[n] = v.ss + best[v.ff];
bind[n] = bind[v.ff] == 0 ? v.ff : bind[v.ff];
}
//mdown[n].insert(v.ss + best[v.ff]);
} else {
up[n] = v.ss;
}
}
}
void reroot(int u, int v, ll w) {
tup[u] -= tup[v] + up[v];
up[u] = w;
tup[v] += tup[u] + up[u];
//mdown[u].erase(mdown[u].find(w + best[v]));
//best[u] = (mdown[u].size() ? *prev(mdown[u].end()) : 0);
//mdown[v].insert(best[u] + up[v]);
//best[v] = max(best[v], best[u] + up[v]);
up[v] = 0;
}
int type = 1;
ll ans = 0;
void solve(int n, int par) {
ans = max(ans, tup[n]);
for (auto v:adj[n]) {
if (v.ff != par) {
ll tmp = up[v.ff];
reroot(n, v.ff, v.ss);
solve(v.ff, n);
reroot(v.ff, n, tmp);
}
}
}
int main() {
io
int n;
cin >> n;
ll tot = 0;
for (int i = 0;i < n - 1;i++) {
int a, b, c, d;
cin >> a >> b >> c >> d;
tot += c + d;
adj[a].push_back(make_pair(b, c));
adj[b].push_back(make_pair(a, d));
}
int q;
cin >> q;
for (int i = 0;i < q;i++) {
int t;
cin >> t;
if (t == 1) {
dfs(1, 0);
solve(1, 0);
} else {
dfs(1, 0);
int p = bind[1];
for (int j = 1;j <= n;j++) tup[j] = 0, up[j] = 0, best[j] = 0, bind[j] = 0;
dfs(p, 0);
ans = tup[p] + best[p];
}
cout << tot - ans << '\n';
}
}
/*
4
1 2 1 2
1 3 3 4
1 4 5 6
1
2
*/
# | 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... |