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;
#define fi first
#define se second
#define ll long long
#define dbg(v) cerr<<#v<<" = "<<v<<'\n'
#define vi vector<int>
#define vl vector <ll>
#define pii pair<int,int>
#define vii vector < pii >
#define mp make_pair
#define db long double
#define pb push_back
#define all(s) s.begin(),s.end()
template < class P , class Q > ostream& operator<<(ostream& stream, pair < P , Q > v){ stream << "(" << v.fi << ',' << v.se << ")"; return stream;}
template < class T > ostream& operator<<(ostream& stream, const vector<T> v){ stream << "[ "; for (int i=0; i<(int)v.size(); i++) stream << v[i] << " "; stream << "]"; return stream;}
template < class T > T smin(T &a,T b) {if (a > b) a = b;return a;}
template < class T > T smax(T &a,T b) {if (a < b) a = b;return a;}
const int N = 1e6 + 5;
map < int , int > cost[N];
set < int > g[N];
ll Answer[N];
ll sum = 0;
ll dfs(int node,int prev) {
ll cnt = 0;
for (auto it : g[node])
if (it != prev)
cnt += dfs(it,node) + cost[it][node];
return cnt;
}
void DFS(int node,int prev) {
smax(Answer[1],sum);
for (auto it : g[node])
if (it != prev) {
sum -= cost[it][node] - cost[node][it];
DFS(it,node);
sum += cost[it][node] - cost[node][it];
}
}
int main(void) {
int n;
cin.tie(0);
ios_base :: sync_with_stdio(0);
cin>>n;
ll Sum = 0;
for (int i = 1;i < n;++i) {
int u,v,a,b;
cin>>u>>v>>a>>b;
cost[u][v] = a;
cost[v][u] = b;
g[u].insert(v);
g[v].insert(u);
Sum += a + b;
}
sum = dfs(1,0);
DFS(1,0);
Answer[1] = Sum - Answer[1];
priority_queue < pair < ll , int > , vector < pair < ll , int > > , greater < pair < ll , int > > > Q;
auto par = [&](int node) {
return *g[node].begin();
};
for (int i = 1;i <= n;++i)
if (g[i].size() == 1)
Q.push(mp(cost[par(i)][i],i));
int sz = Q.size() - 1;
while (sz > 1) {
ll cst = Q.top().fi;
int node = Q.top().se;
Q.pop();
const int Par = par(node);
g[Par].erase(node);
if (g[Par].size() == 1)
Q.push(mp(cst + cost[par(Par)][Par],Par));
else {
Answer[sz] = Answer[sz + 1] + cst;
--sz;
}
}
int q;
cin>>q;
while (q --) {
int cnt;
cin>>cnt;
cout << Answer[cnt] << '\n';
}
return 0;
}
# | 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... |