#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
int n,m,a[6];
vector<pii> adj[50001];
int level[50001],p[50001][17],dis[50001];
void dfs(int x, int par) {
level[x]=level[par]+1;
p[x][0]=par;
for (int i=1; i<=16; ++i) {
p[x][i]=p[p[x][i-1]][i-1];
}
for (auto s : adj[x]) {
if (s.first==par) continue;
dis[s.first]=dis[x]+s.second;
dfs(s.first,x);
}
}
int lca(int x, int y) {
if (level[x]<level[y]) swap(x,y);
int dif=level[x]-level[y];
for (int i=0; i<=16; ++i) {
if (dif&(1<<i)) x=p[x][i];
}
if (x==y) return x;
for (int i=16; i>=0; --i) {
if (p[x][i]!=p[y][i]) {
x=p[x][i];
y=p[y][i];
}
}
return p[x][0];
}
int dist(int x, int y) {
return dis[x]+dis[y]-2*dis[lca(x,y)];
}
void solve() {
for (int i=1; i<=5; ++i) cin>>a[i];
int top_node, min_level=INT_MAX;
for (int i=2; i<=5; ++i) {
int node=lca(1,a[i]);
if (level[node]<min_level) {
min_level=level[node];
top_node=node;
}
}
vector<pii> v; //(level,node)
for (int i=1; i<=5; ++i) v.push_back(pii(level[a[i]],a[i]));
sort(v.begin(),v.end());
int ans=0;
for (int i=0; i<5; ++i) {
int node=v[i].second;
int mmin=dist(top_node,node);
for (int j=0; j<i; ++j) mmin=min(mmin,dis[node]-dis[lca(node,v[j].second)]);
ans+=mmin;
}
cout<<ans<<"\n";
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
cin>>n;
for (int i=0; i<n-1; ++i) {
int x,y,w;
cin>>x>>y>>w;
adj[x].push_back(pii(y,w));
adj[y].push_back(pii(x,w));
}
dfs(0,0);
cin>>m;
while (m--) solve();
}
Compilation message
roadsideadverts.cpp: In function 'void solve()':
roadsideadverts.cpp:42:35: warning: 'top_node' may be used uninitialized in this function [-Wmaybe-uninitialized]
42 | return dis[x]+dis[y]-2*dis[lca(x,y)];
| ~~~^~~~~
roadsideadverts.cpp:47:9: note: 'top_node' was declared here
47 | int top_node, min_level=INT_MAX;
| ^~~~~~~~
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
1492 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
61 ms |
9444 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
26 ms |
7760 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
1492 KB |
Output is correct |
2 |
Incorrect |
61 ms |
9444 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |