Submission #1159855

#TimeUsernameProblemLanguageResultExecution timeMemory
1159855gelastropodJanjetina (COCI21_janjetina)C++20
0 / 110
1 ms328 KiB
#include <bits/stdc++.h>
using namespace std;
#define int long long

signed main() {
    int n, K, x, y, w;
    cin >> n >> K;
    vector<vector<pair<int, int>>> adjlist(n, vector<pair<int, int>>());
    for (int i = 0; i < n - 1; i++) {
        cin >> x >> y >> w;
        x--, y--;
        adjlist[x].push_back({y, w});
        adjlist[y].push_back({x, w});
    }
    queue<int> bfs;
    vector<bool> visited(n, false);
    bfs.push(0);
    visited[0] = true;
    vector<vector<pair<int, int>>> p(60, vector<pair<int, int>>(n, {-1, -1}));
    vector<int> depth(n, 0);
    while (!bfs.empty()) {
        int i = bfs.front();
        bfs.pop();
        for (auto j : adjlist[i]) {
            if (!visited[j.first]) {
                bfs.push(j.first);
                visited[j.first] = true;
                p[0][j.first] = {i, j.second};
                depth[j.first] = depth[i] + 1;
            }
        }
    }
    for (int i = 1; i < 60; i++) {
        for (int j = 0; j < n; j++) {
            if (p[i - 1][j].first == -1) continue;
            if (p[i - 1][p[i - 1][j].first].first == -1) continue;
            p[i][j] = {p[i - 1][p[i - 1][j].first].first, max(p[i - 1][j].second, p[i - 1][p[i - 1][j].first].second)};
        }
    }
    int ans = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (i == j) continue;
            int ci = i, cj = j;
            if (depth[ci] < depth[cj]) swap(ci, cj);
            int maxW = 0;
            int l = 0;
            for (int k = 59; k >= 0; k--) {
                if (abs(depth[i] - depth[j]) & (1LL << k)) {
                    maxW = max(maxW, p[k][ci].second);
                    ci = p[k][ci].first;
                    l += (1LL << k);
                }
            }
            if (ci == cj && maxW - l >= K) {
                ans++;
                continue;
            }
            for (int k = 59; k >= 0; k--) {
                if (p[k][ci].first == p[k][cj].first) continue;
                maxW = max(maxW, p[k][ci].second);
                ci = p[k][ci].first;
                l += (1LL << k);
                maxW = max(maxW, p[k][cj].second);
                cj = p[k][cj].first;
                l += (1LL << k);
            }
            maxW = max(maxW, max(p[0][ci].second, p[0][cj].second));
            l += 2;
            if (maxW - l >= K) {
                ans++;
            }
        }
    }
    cout << ans << '\n';
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...