#include<bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int, int> pii;
typedef vector<pii> vp;
typedef vector<vp> vvp;
vvp graph;
vp par;
void dfs(int v, int p, int w) {
par[v] = { p, w };
for (pii curr : graph[v]) {
int u = curr.first;
int w = curr.second;
if (u != p)dfs(u, v, w);
}
}
void init(int N, vector<int> V, vector<int> U, vector<int> W) {
graph.resize(N);
par.resize(N);
for (int i = 0;i < N - 1;i++) {
graph[V[i]].push_back({ U[i],W[i] });
graph[U[i]].push_back({ V[i],W[i] });
}
}
int query(int a, int b, int c, int d, int e) {
vi nodes = { a,b,c,d,e };
vector<bool> visited(graph.size());
dfs(a, a, 0);
int ans = 0;
for (int i = 1;i < nodes.size();i++) {
int v = nodes[i];
while (!visited[v]) {
visited[v] = true;
ans += par[v].second;
v = par[v].first;
}
}
return ans;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int N, Q;
cin >> N;
vi V(N - 1), U(N - 1), W(N - 1);
for (int i = 0;i < N - 1;i++)cin >> V[i] >> U[i] >> W[i];
init(N, V, U, W);
cin >> Q;
for (int i = 0;i < Q;i++) {
int a, b, c, d, e;
cin >> a >> b >> c >> d >> e;
cout << query(a, b, c, d, e) << endl;
}
return 0;
}
Compilation message
roadsideadverts.cpp: In function 'int query(int, int, int, int, int)':
roadsideadverts.cpp:39:22: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
39 | for (int i = 1;i < nodes.size();i++) {
| ~~^~~~~~~~~~~~~~
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
348 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
1046 ms |
7292 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
124 ms |
5720 KB |
Output is correct |
2 |
Correct |
242 ms |
6920 KB |
Output is correct |
3 |
Correct |
243 ms |
6780 KB |
Output is correct |
4 |
Correct |
239 ms |
6948 KB |
Output is correct |
5 |
Correct |
233 ms |
6920 KB |
Output is correct |
6 |
Correct |
240 ms |
6920 KB |
Output is correct |
7 |
Correct |
233 ms |
6928 KB |
Output is correct |
8 |
Correct |
251 ms |
6976 KB |
Output is correct |
9 |
Correct |
236 ms |
6928 KB |
Output is correct |
10 |
Correct |
230 ms |
6920 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
348 KB |
Output is correct |
2 |
Execution timed out |
1046 ms |
7292 KB |
Time limit exceeded |
3 |
Halted |
0 ms |
0 KB |
- |