#include <bits/stdc++.h>
using namespace std;
#define v first
#define cost1 second.first
#define cost2 second.second
const int N=200001;
vector <pair<int,pair<int,int>>> adj[N];
vector<int> subTrees[N];
int timer,tin[N],tout[N];
long long totalUp,totalDown,down[N],up[N],maxNotInSub[N],maxDown[N],ans[N];
map<long long ,int> Map;
dfs(int u, int p, int id) {
tin[u] = timer++;
long long max1=down[u];
long long max2=0;
maxDown[u] = down[u];
subTrees[id].push_back(u);
int newId = id;
for (auto nxt : adj[u]) {
int v = nxt.v;
if (v == p)
continue;
up[v] = up[u] + nxt.cost2;
totalUp += nxt.cost2;
down[v] = down[u] + nxt.cost1;
totalDown += nxt.cost1;
dfs(v, u, p == -1 ? ++newId : newId);
if(maxDown[v]>max2){
max2=maxDown[v];
}
if(max2>max1)
swap(max2,max1);
maxDown[u] = max(maxDown[u], maxDown[v]);
}
tout[u] = timer - 1;
Map[down[u]]++;
ans[2]=max(ans[2],max1+max2-down[u]-up[u]);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(NULL);
int n;
cin>>n;
timer=0;
for(int u=0;u<n;u++){
down[u]=0;
up[u]=0;
ans[u+1]=0;
maxNotInSub[u]=0;
}
for (int i = 1; i < n; i++) {
int u,v,c1,c2;
cin>>u>>v>>c1>>c2;
u--;
v--;
adj[u].push_back({v,{c1,c2}});
adj[v].push_back({u,{c2,c1}});
}
dfs(0, -1, 0);
ans[2]+=totalUp;
for (int col = 1; col < n; col++) {
for (int u : subTrees[col]) {
Map[down[u]]--;
if(Map[down[u]]==0)
Map.erase(down[u]);
}
long long max=Map.rbegin()->first;
for (int u : subTrees[col]) {
Map[down[u]]++;
maxNotInSub[u] = max;
}
}
// System.out.println(Arrays.toString(maxNotInSub));
for (int u = 0; u < n; u++) {
ans[1] = max(ans[1], totalUp - up[u] + down[u]);
// long long curr = 0;
// // u and root
// curr = totalUp + down[u];
// ans[2] = max(ans[2], curr);
// // u and some child for u
// curr = totalUp - up[u] + maxDown[u];
// ans[2] = max(ans[2], curr);
// // u and some node v such that lca(v,u) = root
// curr = totalUp + down[u] + maxNotInSub[u];
// ans[2] = max(ans[2], curr);
}
int q;
cin>>q;
while (q-- > 0) {
int t;
cin>>t;
cout<<(totalUp + totalDown -ans[t])<<"\n";
}
}
Compilation message
designated_cities.cpp:14:26: error: ISO C++ forbids declaration of 'dfs' with no type [-fpermissive]
dfs(int u, int p, int id) {
^
designated_cities.cpp: In function 'int dfs(int, int, int)':
designated_cities.cpp:42:2: warning: no return statement in function returning non-void [-Wreturn-type]
}
^