#include <bits/stdc++.h>
#define ll long long
#define int ll
#define pii pair<int, int>
#define ff first
#define ss second
#define pb push_back
#define in insert
#define all(x) (x).begin(), (x).end()
#define sz(x) (int)x.size()
#define deb(x) cout << #x << " = " << x << '\n';
#define file(x) freopen(x".in", "r", stdin), freopen(x".out", "w", stdout)
using namespace std;
// const int dx[] = {0, 1, 0, -1};
// const int dy[] = {1, 0, -1, 0};
const int inf = 1e9;
const ll INF = 1e18;
const int mod = 1e9 + 7;
const int N = 1e5 + 2;
int n, q, tin[N], tout[N], timer, up[N][20], pref[N], ans, a[105];
vector <pii> g[N];
map <int, bool> m;
void dfs(int v, int p) {
tin[v] = ++timer;
up[v][0] = p;
for(int i = 1; i <= 19; i++) {
up[v][i] = up[up[v][i - 1]][i - 1];
}
for(auto to:g[v]) {
if(to.ff == p) continue;
pref[to.ff] = pref[v] + to.ss;
dfs(to.ff, v);
}
tout[v] = timer;
}
int get(int v) {
int cnt = 0;
for(int i = 1; i <= 5; i++) {
if(tin[v] <= tin[a[i]] && tout[a[i]] <= tout[v]) cnt++;
}
return cnt;
}
void go(int v) {
int cur = v, cnt = get(v);
for(int i = 19; i >= 0; i--) {
if(get(up[cur][i]) == cnt) cur = up[cur][i];
}
cur = up[cur][0];
ans += pref[v] - pref[cur];
m[v] = 1;
if(!m[cur]) go(cur);
}
void solve() {
cin >> n;
for(int i = 1; i <= n - 1; i++) {
int u, v, w;
cin >> u >> v >> w;
u++;
v++;
g[u].pb({v, w});
g[v].pb({u, w});
}
dfs(1, 1);
cin >> q;
while(q--) {
for(int i = 1; i <= 5; i++) {
cin >> a[i];
a[i]++;
}
m.clear();
int v = a[1];
for(int i = 19; i >= 0; i--) {
if(get(up[v][i]) != 5) v = up[v][i];
}
m[up[v][0]] = 1;
ans = 0;
for(int i = 1; i <= n; i++) {
if(!m[a[i]]) go(a[i]);
}
cout << ans << '\n';
}
}
signed main() {
ios_base::sync_with_stdio(0), cin.tie(0);
int TT = 1;
// cin >> TT;
while(TT--) {
solve();
}
return 0;
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
4696 KB |
Output is correct |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Runtime error |
31 ms |
34640 KB |
Execution killed with signal 11 |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
888 ms |
16832 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
4696 KB |
Output is correct |
2 |
Runtime error |
31 ms |
34640 KB |
Execution killed with signal 11 |
3 |
Halted |
0 ms |
0 KB |
- |