1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| #include <bits/stdc++.h> #define mid(l, r) (l + ((r - l) >> 1)) #define sz(x) (int(x.size())) #define repeat(i, a, b) for (int i = (a); i <= (b); i++) #define until(i, a, b) for (int i = (a); i >= (b); i--) #define array_of(T) std::unique_ptr<T[]> #define all(x) x.begin(), x.end() #define range(x, a, b) x + a, x + b + 1 using ll = long long; using vi = std::vector<int>; using pii = std::pair<int, int>; using pli = std::pair<ll, int>;
constexpr int N = 5005; constexpr ll inf = 1e18;
int n, m; std::vector<pli> G[N], H[N]; ll map[N][N], dp[N][N];
void Run() { std::cin >> n >> m; repeat(i, 1, n - 1) { int u, v, w; std::cin >> u >> v >> w; G[u].push_back({w, v}); G[v].push_back({w, u}); } repeat(i, 1, m) { int u, v; std::cin >> u >> v; H[u].push_back({0, v}); H[v].push_back({0, u}); } auto source = [&](int s) { repeat(i, 1, n) map[s][i] = inf; map[s][s] = 0;
auto dfs = [&](auto F, int u, int fa) -> void { for (auto [w, v] : G[u]) { if (v == fa) continue; map[s][v] = map[s][u] + w; F(F, v, u); } }; dfs(dfs, s, s); }; repeat(i, 1, n) source(i); ll sum = 0; repeat(i, 1, n) { dp[0][i] = map[1][i]; sum += dp[0][i]; } std::cout << sum << "\n";
repeat(depth, 1, n) { ll sum = 0; repeat(i, 1, n) dp[depth][i] = dp[depth - 1][i]; using node = std::pair<ll, int>; std::priority_queue<node, std::vector<node>, std::greater<node>> q; repeat(u, 1, n) for (auto [w, v] : H[u]) { if (dp[depth][v] > dp[depth - 1][u]) { dp[depth][v] = dp[depth - 1][u]; q.push({dp[depth][v], v}); } }
while (!q.empty()) { auto [d, u] = q.top(); q.pop();
if (dp[depth][u] < d) continue; for (auto [w, v] : G[u]) { if (dp[depth][v] > dp[depth][u] + w) { dp[depth][v] = dp[depth][u] + w; q.push({dp[depth][v], v}); } } }
repeat(i, 1, n) sum += dp[depth][i]; std::cout << sum << "\n"; } }
int main() { std::cin.tie(0)->sync_with_stdio(0); std::cout.tie(0), std::cerr.tie(0);
int t = 1; while (t--) Run(); }
|