/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 4ms 5.336 MiB
#2 Accepted 5ms 7.773 MiB
#3 Accepted 5ms 8.023 MiB
#4 Accepted 4ms 5.035 MiB
#5 Accepted 5ms 6.074 MiB
#6 Accepted 5ms 8.109 MiB
#7 Accepted 19ms 8.25 MiB
#8 Accepted 18ms 6.832 MiB
#9 Accepted 18ms 5.406 MiB
#10 Accepted 19ms 8.145 MiB
#11 Accepted 243ms 19.918 MiB
#12 Accepted 238ms 19.992 MiB
#13 Accepted 241ms 20.039 MiB
#14 Accepted 235ms 19.934 MiB
#15 Accepted 122ms 9.066 MiB
#16 Accepted 126ms 12.922 MiB
#17 Accepted 124ms 8.77 MiB
#18 Accepted 123ms 10.789 MiB
#19 Accepted 124ms 8.809 MiB
#20 Accepted 127ms 13.109 MiB

Code

#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#include <cmath>
using namespace std;

const int MAXN = 100000;
const int LOG = 17;

vector<pair<int, int>> adj[MAXN + 1];
int up[MAXN + 1][LOG];
int maxEdge[MAXN + 1][LOG];
int depth[MAXN + 1];

void dfs(int node, int parent, int weight) {
    up[node][0] = parent;
    maxEdge[node][0] = weight;
    for (int i = 1; i < LOG; i++) {
        up[node][i] = up[up[node][i-1]][i-1];
        maxEdge[node][i] = max(maxEdge[node][i-1], maxEdge[up[node][i-1]][i-1]);
    }

    for (auto &[next, w] : adj[node]) {
        if (next != parent) {
            depth[next] = depth[node] + 1;
            dfs(next, node, w);
        }
    }
}
int query(int u, int v) {
    if (depth[u] < depth[v]) swap(u, v);
    int maxRes = INT_MIN;

    for (int i = LOG - 1; i >= 0; i--) {
        if (depth[u] - (1 << i) >= depth[v]) {
            maxRes = max(maxRes, maxEdge[u][i]);
            u = up[u][i];
        }
    }

    if (u == v) return maxRes;

    for (int i = LOG - 1; i >= 0; i--) {
        if (up[u][i] != up[v][i]) {
            maxRes = max({maxRes, maxEdge[u][i], maxEdge[v][i]});
            u = up[u][i];
            v = up[v][i];
        }
    }

    maxRes = max({maxRes, maxEdge[u][0], maxEdge[v][0]});
    return maxRes;
}

int main() {
    int N;
    cin >> N;
    int K; cin >> K;

    for (int i = 1; i < N; i++) {
        int A, B, C;
        cin >> A >> B >> C;
        adj[A].emplace_back(B, C);
        adj[B].emplace_back(A, C);
    }

    for (int i = 1; i <= N; i++) {
        for (int j = 0; j < LOG; j++) {
            up[i][j] = -1;
            maxEdge[i][j] = INT_MIN;
        }
    }

    // Preprocess
    // depth[1] = 0;
    dfs(1, -1, 0);

    // Queries
    while (K--) {
        int D, E;
        cin >> D >> E;
        auto maxLength = query(D, E);
        cout << maxLength << "\n";
    }

    return 0;
}

Information

Submit By
Type
Submission
Problem
P1019 Graph Stuff
Language
C++17 (G++ 13.2.0)
Submit At
2025-01-22 12:37:37
Judged At
2025-01-22 12:37:37
Judged By
Score
100
Total Time
243ms
Peak Memory
20.039 MiB