Question
Minimal path on weighted tree query
Given a weighted tree with n vertices. there are q queries and for each query, you are given integers (u,k). find number of vertices v such that the smallest edge on the route from u to v is equal to k. (n,q <= 1e5)
i tried using dfs but the best solution i could think is O(n*q)
My current code:
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
struct Edge {
int to;
int weight;
};
vector<vector<Edge>> adj;
vector<int> mn;
void dfs(int u, int parent, int minWeight) {
mn[u] = minWeight;
for (auto edge : adj[u]) {
if (edge.to != parent) {
dfs(edge.to, u, min(minWeight, edge.weight));
}
}
}
int main() {
int n, q;
cin >> n >> q;
adj.resize(n + 1);
mn.resize(n + 1);
for (int i = 0; i < n - 1; ++i) {
int u, v, w;
cin >> u >> v >> w;
adj[u].push_back({v, w});
adj[v].push_back({u, w});
}
while (q--) {
int u, k;
cin >> u >> k;
fill(mn.begin(), mn.end(), INF);
dfs(u, -1, INF);
int cnt = 0;
for (int v = 1; v <= n; ++v) {
if (v != u && mn[v] == k) {
cnt++;
}
}
cout << cnt << endl;
}
return 0;
}