이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include<bits/stdc++.h>
#define ll long long
#define pll pair<ll, ll>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define ld long double
#define sz(a) ((ll)(a).size())
using namespace std;
struct edge
{
ll v, c, d;
edge(){}
edge(ll v, ll c, ll d): v(v), c(c), d(d){}
};
const ll maxn=200005;
priority_queue <ll> q[maxn];
ll ans[maxn], C[maxn], D[maxn];
pair<pll, pll> dp[maxn];
vector <edge> A[maxn];
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
ll n, sum=0, allup=0, root=0, crm=0; cin >> n;
for (ll i=1; i<n; i++)
{
ll u, v, c, d; cin >> u >> v >> c >> d;
A[u].pb({v, c, d}), A[v].pb({u, d, c});
sum+=c, sum+=d;
}
function <void(ll, ll)> dfs=[&](ll u, ll pa)
{
ans[1]=max(ans[1], C[u]-D[u]), dp[u].fi={0, u};
for (auto [v, c, d]:A[u])
{
if (v==pa) continue;
C[v]=C[u]+c, D[v]=D[u]+d, allup+=d, dfs(v, u);
pll val={dp[v].fi.fi+c, dp[v].fi.se};
if (val>dp[u].fi) dp[u].se=dp[u].fi, dp[u].fi=val;
else if (val>dp[u].se) dp[u].se=val;
}
ll val=C[u]-D[u]+dp[u].fi.fi+dp[u].fi.se;
if (val>crm) root=dp[u].fi.se, crm=val;
}; dfs(1, 1), ans[1]=sum-(ans[1]+allup), allup=0;
function <void(ll, ll)> dfs2=[&](ll u, ll pa)
{
vector <ll> num;
for (auto [v, c, d]:A[u])
{
if (v==pa) continue;
C[v]=C[u]+c, allup+=d;
dfs2(v, u), num.pb(q[v].top()), q[v].pop();
}
if (!sz(num)) {q[u].push(C[u]); return;}
sort(num.begin(), num.end(), greater<ll>());
for (ll i=0; i<sz(num); i++)
q[u].push(i?num[i]-C[u]:num[i]);
for (auto [v, c, d]:A[u])
if (v!=pa)
{
if (sz(q[u])<sz(q[v])) swap(q[u], q[v]);
while (sz(q[v])) q[u].push(q[v].top()), q[v].pop();
}
}; C[root]=0, dfs2(root, root);
for (ll i=2, s=0; i<=n; i++)
{
if (q[root].empty()) {ans[i]=ans[i-1]; continue;}
s+=q[root].top(), q[root].pop();
ans[i]=sum-(allup+s);
}
ll q; cin >> q;
while (q--) {ll x; cin >> x; cout << ans[x] << "\n";}
}
# | 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... |